/*============================================================================
 Name        : MyDataCenter.cpp
 Author      : 
 Version     :
 Copyright   : iTest 2007
 Description : CMyDataCenter implementation
============================================================================
*/
#include "xml\SyExpat.h"
#include "xml\SyGen.h"
#include <e32test.h>
#include <aknutils.h>
#include <APGCLI.H> //for RApaLsSession
 
#include "xml\feedbackhelper.h"

#include "ui\mypicture.h"
#include "ui\DynAddDlg.h"
#include "iTestAppUi.h"

#include "MyDataCenter.h"
#include "plugin.h"
#include "ui\mydialog.h"
#include "ui\mywaitdlg.h"
#include "CImageHandler.h"
#include "ITest.hrh"

//db
////#include "CBtEngine.h"
////#include "BluetoothPMPExampleEngine.h"
#include "FileDebug.h"

#include <iTest_0xE0D9648A.rsg>

#include <BAUTILS.H>
#include <COEUTILS.H>
#include <utf.h>
#include <html\htmlcontrol.h>

c4_Storage* gDBStore = NULL;
CHtmlControl* gHtmlControl = NULL;

FileDebug* mydebug;
CHtmlElement* iList; 

//for special bug
int largeimagebuf = 0;
int snapimagebuf = 0;
//
#ifdef _DEBUG			
	#define CategoryCheckTime 3
#else
	#define CategoryCheckTime 1800 //86400
#endif			

enum TaskCommandEnum
{
	//system
	task_login2,	
	task_login_bt,	
	task_update,
	
	//mail function	
	mail_choosema, //choose mail account
	mail_config, //post and page function
	mail_check_list,//post
	mail_check_list2,//post	
	mail_read_content,//post
	mail_read_content2,//post	
	mail_send,//post
	mail_reply,
	news_read_content,//post
		
	//mail page function
	func_mailenter,	
	func_maillist,
	func_readmail,
	
	//stock page function
	stock_info,
	stock_query,	
	stock_img,
	mystock_add,
	mystock_info,
	
	//club
	club_friendadd,
	club_friendsearch,
	club_pf_friendlist,	
	
	//newsbbs page function
	func_channellist,
	func_downimage,
	func_newslist,
	func_readnews,
	func_sitelist,
	func_viewimage,
	news_checklist,	
	news_checkcategory,
	
	func_test,
	func_plugin,
	task_error,
	task_info,
	task_comand_enum_size
};

const char* TaskCommands[] = 
{
	//post
	"login2",
	"login_bt",	
	"update",

	"mail_choosema",
	"mail_config",
	"mail_checklist",
	"mail_checklist2",	
	"mail_readcontent",
	"mail_readcontent2",	
	"mail_send",
	"mail_reply",
	"news_readcontent",	
	
	//mail page function
	"mailenter",
	"pfunc_maillist",
	"pfunc_readmail",
	
	//stock page function
	"stock_info",//股票信息
	"stock_query",//股票信息查询
	"pfunc_stockimg", //股票行情图
	"mystock_add", //增加自选股
	"mystock_info", //自选股行情
	
	//club
	"club_friendadd",	
	"club_friendsearch",
	"club_pf_friendlist",//page func
	
	//newsbbs page function
	"pfunc_channellist",	
	"pfunc_downimage",	
	"pfunc_newslist",
	"pfunc_readnews",
	"pfunc_sitelist",
	"pfunc_viewimage",
	"news_checklist",
	"news_checkcategory",//检查category是否更新	
	
	"test",
	"plugin",
	//error
	"error",
	"info"
	
};

class CTestOutput : public CBase, public MSyOutputHandler
{
public:
	CTestOutput(){TBuf8<100> dump; iBuffer = dump.AllocL();};
	~CTestOutput(){delete iBuffer;};
	HBufC8* iBuffer;
	virtual void WriteL(const TDesC& aString, const TBool aIsRawData)
	{
		TPtrC ptr(aString);
		iBuffer = iBuffer->ReAllocL(iBuffer->Length() + aString.Length());
		iBuffer->Des().Append(aString);
		return;
		_LIT(KFormat, "%S");
//		test.Printf(KFormat, &ptr);
		
		if (!aIsRawData)
		{
			_LIT(KNewLine, "\n");
			
			const TInt last = aString.Length()-1;
			
			if (aString[last-1] == TChar('/') && aString[last] == TChar('>'))
			{
//				test.Printf(KNewLine);
			}
			else
			{			
				// if the start is "</" or "<!" or "<?" or the end is "/>" and it is not raw data
				// then print a new line 
				if (aString[0] == TChar('<'))
				{
					
					if (aString[1] == TChar('/') || aString[1] == TChar('!') || aString[1] == TChar('?'))
					{
//						test.Printf(KNewLine);
					}
				}
			}
		}
	}
};

class MyStr16
{
public:	
	MyStr16(const TDesC8& source)
	{
		ibuf = HBufC::NewL(source.Length());
		TPtr ptr = ibuf->Des();
		ptr.Copy(source);
		
	};
	~MyStr16()
	{
		delete ibuf;
	};
	const TPtrC Value(){return ibuf->Des();};
private:
	HBufC* ibuf;		
};

class MyUnicode2Utf8
{
public:	
	MyUnicode2Utf8(TDesC16 &aUnicode)
	{
		ibuf8 = NULL;
		ibuf = NULL;
		ToUtf8FromUnicode(aUnicode);
	};

	void ToUtf8FromUnicode(TDesC16 &aUnicode)
	{
		if(ibuf8) delete ibuf8;
		if(ibuf) delete ibuf;
		
		int len = aUnicode.Length() * 3 + 1;
		ibuf8 = HBufC8::NewL(len);
		ibuf = HBufC::NewL(len);	
		TPtr8 ptrUtf8 = ibuf8->Des();		
		CnvUtfConverter::ConvertFromUnicodeToUtf8(ptrUtf8, aUnicode);			
		ibuf->Des().Copy(ptrUtf8);
	};
	TPtrC Ptr()
	{
		return ibuf->Des();
	};
	
	TPtrC8 Ptr8()
	{
		return ibuf8->Des();
	};
	
	~MyUnicode2Utf8()
	{
		delete ibuf8;
		delete ibuf;
	};

private:
	HBufC8* ibuf8;
	HBufC* ibuf;	
};

int mystrlen(const char* str)
{
	int len = 0; 
	while(str[len] != 0) len++;
	return len;
}

int CommandIndex(const TDesC& commandstr)
{
	//get command
	TBuf8<128> cmdpara8;
	cmdpara8.Copy(commandstr);
	
	int commandid = -1;
	//get index of this command
	for(int i = 0; i < task_comand_enum_size; i++)
	{
	    TPtrC8 ptr8;
    	ptr8.Set( (const TUint8*)TaskCommands[i], mystrlen(TaskCommands[i]) );	
		if(cmdpara8 == ptr8)
		{
			commandid = i;			
			break;
		}
	}
	
	return commandid;
}

//get function name and its parameters from an url
//e.g., if the str is "test/demo/index.xml?myfunc(x1,x2)
//the result function name is "myfunc", and its parameters
//has two, "x1" and "x2"
//so PageUrlInfo[0]-url name, PageUrlInfo[1]-func name
//URLInfo[2...] - parameters.

void getfuncpara(const TDesC& paras, URLInfo& aUrlInfo)
{
	if(aUrlInfo.Count() != 0)
		return;

	TBuf<256> buf;
	aUrlInfo.Append(buf);//for url, or xml itself
	aUrlInfo.Append(buf);//for fuanciton name
	aUrlInfo.Append(buf);//for para1
	aUrlInfo.Append(buf);//for para2	
	
	int len = paras.Length();	
	int pos = paras.Locate('?');
	if(pos == KErrNotFound)
	{
		aUrlInfo[0].Copy(paras);
		aUrlInfo[0].Trim();		
		return;
	}
	
	aUrlInfo[0].Copy(paras.Left(pos));
	aUrlInfo[0].Trim();

	buf.Copy(paras.Right(len-pos-1));
	//

	pos = buf.Locate('(');
	if(pos == KErrNotFound) //only func without parameters
	{
		aUrlInfo[1].Copy(buf);
		aUrlInfo[1].Trim();		
		return;
	}
	
	//
	aUrlInfo[1].Copy(buf.Left(pos));
	aUrlInfo[1].Trim();	

	len = buf.Length();
	buf = buf.Mid(pos+1, len-pos-2); //get part between "(" and ")"

	len = buf.Length();
	pos = buf.Locate(',');
	if(pos == KErrNotFound) 
	{
		aUrlInfo[2].Copy(buf);		
		aUrlInfo[2].Trim();		
	}
	else
	{
		aUrlInfo[2].Copy(buf.Left(pos));
		aUrlInfo[2].Trim();
		aUrlInfo[3].Copy(buf.Right(len-pos-1));
		aUrlInfo[3].Trim();
	}
}


CMyDataCenter::CMyDataCenter()
{
	iHttpPosting = false;
	iImgDownloading = false;
	
	iAntiLock = 0;
	m_pageIntVar = 0;
	iHistory = new (ELeave) CDesCArrayFlat(5);		
	iHomePageLoaded = false;
	iTabGroupUid = -1;
	iCurrentCid = -1;
	
	mydebug = NULL; //new FileDebug();
	
	char drive = 'c';
	TBuf<128> imgfile;
	imgfile.Copy(_L("c:\\data\\itest\\images.dat"));
#ifndef _DEBUG
	TFileName fname;
	CompleteWithAppPath( fname );	
//	CEikonEnv::Static()->InfoWinL(_L("test"), fname);
	//char drive = fname[0];	
	if(!ConeUtils::FileExists(_L("c:\\data\\itest\\itest.bdb")))
		{
		drive = 'e';
		imgfile.Copy(_L("e:\\data\\itest\\images.dat"));
		}
#endif

	TBuf8<256> path;

	//db
	char storepath[] = "c:\\data\\itest\\itest.bdb";
	storepath[0] = drive;
	gDBStore = new c4_Storage(storepath, true);	

	char respath[] = "c:\\data\\itest\\res.bdb";
	respath[0] = drive;
	iDBRes = new c4_Storage(respath, false);//只读的资源文件

	char infopath[] = "c:\\data\\itest\\info.bdb";
	infopath[0] = drive;
	iDBInfo = new c4_Storage(infopath, true);//新闻和图片	
	iDBInfo->AutoCommit(true);

	char mailpath[] = "c:\\data\\itest\\mail.bdb";
	mailpath[0] = drive;	
	iDBMail = new c4_Storage(mailpath, true);

	char clubpath[] = "c:\\data\\itest\\club.bdb";
	clubpath[0] = drive;		
	iDBClub = new c4_Storage(clubpath, true);	
	
	char stockpath[] = "c:\\data\\itest\\stocks.bdb";
	stockpath[0] = drive;			
	iDBStock = new c4_Storage(stockpath, true);
	
	char temppath[] = "c:\\data\\itest\\temp.bdb";
	temppath[0] = drive;				
	iDBTemp = new c4_Storage(temppath, true);	
	
	iMyImgFile.Init(imgfile);
	//
	iImageList = new (ELeave) CDesCArrayFlat(6);	
	iImageStart = 0; // for imagecontainer to display
		
////    iEngine = CBtEngine::NewL();
	
    iHttpImgDown = CClientEngine::NewL(100, *this); 
 	iHttpEngine = CClientEngine::NewL(200, *this); 
 	iHttpDownload = CDownloadEngine::NewL();


 	iTempStrBuffer = HBufC::NewL(256);
 	iMenuID = 0; //default menu id

 	iDialog = NULL;
 	iActiveView = NULL;
 	iActiveContainer = NULL;


	//为了控制左右键太快，总是在１秒以后才进行Sync
	iTimer = CMyTimer::NewL(this, 100);
	
	LoadPluginInfo();	
}

CMyDataCenter::~CMyDataCenter()
{
	iLibrary.Close();
	
	if(iTimer)
	{
		iTimer->Cancel();
		delete iTimer;
	}	
		
	delete iHistory;	
	delete iTempStrBuffer;
	
	if(iDialog)
		delete iDialog;

			
	delete mydebug;
	
	if(gDBStore)
	{
		gDBStore->Commit();
		delete gDBStore;
	}	

	if(iDBClub)
	{
		iDBClub->Commit();
		delete iDBClub;
	}	

	if(iDBMail)
	{
		iDBMail->Commit();
		delete iDBMail;			
	}
	if(iDBInfo)
	{
		iDBInfo->Commit();
		delete iDBInfo;			
	}

	delete iDBStock;	
	delete iDBRes;
	delete iDBTemp;

	gHtmlControl->ClearStyleSheet();
////	delete iEngine;
	delete iImageList;
	delete iHttpImgDown;
	delete iHttpEngine;
	delete iHttpDownload;
}

void CMyDataCenter::AddHistory(const TDesC& link)
{
//	CEikonEnv::Static()->InfoWinL(_L("his"), link);

	iHistory->AppendL(link);	
}

void CMyDataCenter::AddSelfHistory(const TDesC& link, bool removecurrent)
{
	TBuf<256> current;
	int count = iHistory->Count();
	if(count == 0)
		return;
	current.Copy( (*(iHistory))[count-1]);

	if(link.Find(_L("self?")) != KErrNotFound)
	{
		int pos = current.Locate('?');
		if(pos == KErrNotFound)
			return;

		TBuf<256> buf;				
		buf.Copy(current.Left(pos+1));
		int len = link.Length();
		buf.Append(link.Right(len-5));
		if(buf != current)
		{
			if(removecurrent)
				iHistory->Delete(count-1);
			iHistory->AppendL(buf);
//		CEikonEnv::Static()->InfoWinL(_L("selfhis"), buf);
		}
		
		return;
	}
}

void CMyDataCenter::LoadPluginInfo()
{
	c4_View view = gDBStore->View("plugin");
	int count = view.GetSize();	
	for(int i = 0; i < count; i++)
	{
		MY_GRIDVIEW_DATA* data = new MY_GRIDVIEW_DATA;
		
		const TPtrC8 temp = FieldStr8Value(&view, "name", i);
		data->name.Copy(temp);
		
		const TPtrC8 img1 = FieldStr8Value(&view, "normal_img", i);
		data->normal_img.Copy(img1);

		const TPtrC8 img2 = FieldStr8Value(&view, "active_img", i);
		data->active_img.Copy(img2);
		
		TPtrC ptr = FieldUnicodeValue(&view, "title", i);
		data->title.Copy(ptr);
		
		iHmGridView.iGridViewData.Append(data);
	}	
}

bool CMyDataCenter::GoBack()
{
	//step1
	if(iHmUtil.IsDivVisible(_L("iFloat")))
	{
		iHmUtil.HideDiv(_L("iFloat"));
		gHtmlControl->RefreshAndDraw();	
		return true;		
	}
	
	//step2
	int count = iHistory->Count();
	if(count == 0)
		return false;

	iHistory->Delete(count-1);
	count = iHistory->Count();
	if(count == 0)
		return false;			

	ProcessLink((*iHistory)[count-1], false);
//TBuf<256> tt;
//tt.Copy((*iHistory)[count-1]);
//iWaitDlg.Note(tt, 3);
	
	return true;
}

//call me at void CiTestPageContainerView::DoActivateL
void CMyDataCenter::LoadHomePage()
{
	if(!iHomePageLoaded)//only once
	{
		LoadMemPage("syspage", _L("template.htm"),false);	
		LoadMemPage("syspage", _L("login.htm?login2"));	
		iHomePageLoaded = true;
	}
}


CiTestAppUi* CMyDataCenter::AppUi()
{
	return (CiTestAppUi*)CEikonEnv::Static()->AppUi();	
}

//修改当前历史url的参数
void CMyDataCenter::ChangeCurrentHistoryPara(const TDesC& newpara)
{
	TBuf<256> current;
	int count = iHistory->Count();
	if(count == 0)
		return;
	current.Copy( (*(iHistory))[count-1]);

	int pos = current.Locate('(');
	if(pos == KErrNotFound)
		return;

	TBuf<256> buf;				
	buf.Copy(current.Left(pos));
	buf.Append(newpara);
	if(buf != current)
	{
		iHistory->Delete(count-1);
		iHistory->AppendL(buf);
	}
}

void CMyDataCenter::ClearImageList()
{
	iImageList->Reset();	
}

void CMyDataCenter::ClientEvent(const int aClientID, const TDesC& aEventDescription)
{

}

void CMyDataCenter::ClientReceived(const int aClientID, const TDesC8& aRevData)
{

}

int bttt = 0;
//notified by connector
/*
 *应该是被CBtEngine通知，但是因为很怪的问题，直接由connector通知 
 * 
 * */
void CMyDataCenter::HandleConnectorDes8ReceivedL(int aHttpClientID, const TDesC8& aData)
{
	//the first 2 bytes is for taskid and callerid
	if (!iResponseBuffer)
		iResponseBuffer = aData.AllocL();
	else
	{
		iResponseBuffer = iResponseBuffer->ReAllocL(iResponseBuffer->Length() + aData.Length());
		iResponseBuffer->Des().Append(aData);
	}
	
	int len = aData.Length();
	
	bttt += len;
	if(len < 40 && len > 0)
	{
		TBuf<100> tt;
		tt.Format(_L("%d"), iResponseBuffer->Length());
		if(aData[len-1] == '\f')
		{
				int remove = 3;
				if(iResponseBuffer->Des()[bttt-1] == '\f' && iResponseBuffer->Des()[bttt-2] == '\r')
					remove = 2;
//			HBufC8* text = HBufC8::NewLC(iResponseBuffer->Length());
//            text->Des().Copy(iResponseBuffer->Des().Right(ttt-2).Left(ttt-2-remove));
				ClientBodyReceived(aHttpClientID, iResponseBuffer->Des().Right(bttt-2).Left(bttt-2-remove));
//				ClientBodyReceived(aHttpClientID, *text);
//            CleanupStack::PopAndDestroy(text);
			
				bttt = 0;
			iResponseBuffer->Des().Copy(_L(""));
		}
	}
}

int CMyDataCenter::Dateline()
{
	TTime baseTime(_L("19700101:080000.000000"));
	TTime aTime;
	aTime.HomeTime();
	
	TTimeIntervalMicroSeconds diff = aTime.MicroSecondsFrom(baseTime);
	int res = diff.Int64()/1000000;
	return res;
}

//查询大图是否已经存在
bool CMyDataCenter::FindPageImage(int pageid, int imgindex)
{
	c4_View view = iDBInfo->View("pagelargeimages");
	int find = FindBy2Int(&view, "pageid", pageid, "orderid", imgindex);
	return (find >= 0);
}	
	
void CMyDataCenter::DownloadPageImage(const TDesC& largepageimage)
{
	iWaitDlg.Note(_L("Loading image..."));	
//	iWaitDlg.Note(largepageimage);		
	TBuf8<256> url8;
	url8.Copy(largepageimage);
	iImgDownTask.method = 3;	
	IssueHTTPGetL(url8, this);
//	CEikonEnv::Static()->InfoWinL(_L("tesT"), largepageimage);				
}
		
void CMyDataCenter::ClientBodyReceived(const int aClientID, const TDesC8& aBodyData)
{
	if(aClientID == iHttpEngine->iClientID)
	{
//mydebug->Write(_L8("dat"), aBodyData);
		iHttpPosting = false;
		CFeedbackHandler feedbackHandler;
		ParseXMLBuffer(aBodyData, &feedbackHandler);
		ParseRemoteFeedback(&feedbackHandler);
	}
	else if(aClientID == iHttpImgDown->iClientID)
	{
		iImgDownloading = false;
		//股票行情图
		if(iImgDownTask.method == 2)		
		{
//			RFs fs;	
//			RFile rf;
//		
//			fs.Connect();
//			User::LeaveIfError(rf.Replace(fs, iImgDownTask.dest, EFileWrite));
//			rf.Write(aBodyData);
//		
//			rf.Close();	fs.Close();	
//			iEditor->iImageHandler->LoadFileL(iImgDownTask.dest);

////			TPtrC8 ptr = aBodyData;
////			iEditor->iImageHandler->LoadBuffer(&ptr, 100);// LoadFileL(iImgDownTask.dest);
		}
		
		//页面预览图
		else if(iImgDownTask.method == 1)
		{
			if(	iAntiLock != iHistory->Count())
			{
				//说明下载小图片时用户可能用了goback.为避免dead,就不继续下去
				return;
			}
			
			TPtrC8 ptr = aBodyData;
						
			int pageid = iImgDownTask.pageid;
			int channel = iImgDownTask.channelid;
			int imagesnum = iImgDownTask.totalnum;
			
			int imgindex = iImgDownTask.imgindex; //1-the first image
			TBuf<256> filename;
			filename.Format(KLocalPreviewImg, pageid, imgindex);
			
			//新增一个图片记录
			c4_View view = iDBInfo->View("pageimages");
			c4_Row row;
			int size = view.GetSize();
			int lastid = (size == 0)?0:FieldIntValue(&view, "id", size-1);

		    SetRowRefIntValue(row, "id", lastid+1);
		    SetRowRefIntValue(row, "pageid", pageid);
		    SetRowRefIntValue(row, "orderid", imgindex);
		    SetRowRefStrValue(row, "imagefile", filename);
		    
			//SetRowRefBinValue(row, "data", ptr);
		    iMyImgFile.SaveToFile(ptr);
		    SetRowRefIntValue(row, "datasize", ptr.Length());
		    SetRowRefIntValue(row, "datapos", iMyImgFile.Length()-ptr.Length());
		    
			view.Add(row);
			TBuf<256> note;
			note.Format(_L("%d images downloaded"),imgindex); 
			iWaitDlg.Note(note, 1);
			//CEikonEnv::Static()->InfoWinL(filename, _L("Just downloaded one image..."));		
		    
			LoadExistImages();
		}
		//大图
		else if(iImgDownTask.method == 3)
		{
			TPtrC8 ptr = aBodyData;
						
			int pageid = iHmPreview.iPageId;
			int imgindex = iHmPreview.iLargeImgOrderId;
			
			TBuf<256> filename;
			filename.Format(KLocalImg, pageid, imgindex);
			
			//新增一个大图片记录
			c4_View view = iDBInfo->View("pagelargeimages");
			c4_Row row;
			int size = view.GetSize();
			int lastid = (size == 0)?0:FieldIntValue(&view, "id", size-1);

		    SetRowRefIntValue(row, "id", lastid+1);
		    SetRowRefIntValue(row, "pageid", pageid);
		    SetRowRefIntValue(row, "orderid", imgindex);
		    SetRowRefStrValue(row, "imagefile", filename);
		    
			//SetRowRefBinValue(row, "data", ptr);
		    iMyImgFile.SaveToFile(ptr);
		    SetRowRefIntValue(row, "datasize", ptr.Length());
		    SetRowRefIntValue(row, "datapos", iMyImgFile.Length()-ptr.Length());
		    
			view.Add(row);	
			iDBInfo->Commit();
			
			TBuf<256> note;
			note.Format(_L("%d 'th lagre image downloaded"),imgindex); 
			iWaitDlg.Note(note, 1);
//			CEikonEnv::Static()->InfoWinL(filename, _L("Just downloaded one image..."));		
			iHmPreview.DisplayLargeImg(imgindex);
		}
		
		else
		{
			RFs fs;	
			RFile rf;
		
			fs.Connect();
			CEikonEnv::Static()->InfoMsg( iImgDownTask.dest );
			User::LeaveIfError(rf.Replace(fs, _L("c:\\data\\itest\\002\\test.jpg"), EFileWrite));
			rf.Write(aBodyData);
		
			rf.Close();	fs.Close();	
		}
	}
}

	
//从资源数据库里读出图片的尺寸信息
bool CMyDataCenter::FastImageInfo(CImageHandler* aImageHandler, const TDesC& aFileName, TSize& size)
{
	c4_View view = iDBRes->View("image");
	
	TBuf8<256> str8;
	str8.Copy(aFileName);
	char* path = (char *)str8.Ptr();
	path[aFileName.Length()] = 0;
	
	int find = FindByStr(&view, "path", path);
	if(find < 0)
		return false;

	TPtrC8 ptr = FieldUtf8Value(&view, "data", find);
	aImageHandler->FastImageInfo(&ptr, size);
		
	return true;	
}	

int CMyDataCenter::FieldIntValue(c4_View* view, char* fieldname, int pos)
{
	c4_IntProp intfield(fieldname);
	int value = intfield((*view)[pos]);
	return value;
}

/*
//有内存遗漏问题。
const TPtrC CMyDataCenter::FieldStrValue(c4_View* view, char* fieldname, int pos)
{
	c4_StringProp strfield(fieldname);
	c4_String str = c4_String(strfield((*view)[pos]));
	TPtrC8 ptr8 = str.Ptr8();
	
	
	
	if(str.GetLength() > 255)
	{
		iTempStrBuffer = iTempStrBuffer->ReAllocL(iTempStrBuffer->Length() + str.GetLength());
	}
	
	TPtr ptr = iTempStrBuffer->Des();
	ptr.Copy(ptr8);;

//	return iTempStrBuffer->Des();
	return *(ptr.Alloc());
}
*/

const TPtrC8 CMyDataCenter::FieldStr8Value(c4_View* view, char* fieldname, int pos)
{
	c4_StringProp strfield(fieldname);
	iStrTemp = c4_String(strfield((*view)[pos]));
	return iStrTemp.Ptr8();
}

TPtrC CMyDataCenter::FieldUnicodeValue(c4_View* view, char* fieldname, int pos, bool carriageconvert)
{
	c4_BytesProp binfield(fieldname);
	c4_Bytes bin;
	bin = binfield(((*view)[pos]));

	const int len = bin.Size()/2;
	if(len == 0) return _L("");

/*该代码有问题，会产生乱码，比如伊拉克的"伊"，看来这个转换得重写
	if(carriageconvert)
	{	
		unsigned char* p = (unsigned char*)bin.Contents();
			
		for(int i = 0; i < len; i++)
		{
			if(p[i] == '\n')
				p[i] = '\f';
		}
	}
*/	
	
	TPtrC ptr((TUint16*)bin.Contents(), bin.Size()/2);
	return ptr;
}

TPtrC8 CMyDataCenter::FieldUtf8Value(c4_View* view, char* fieldname, int pos)
{
	c4_BytesProp binfield(fieldname);
	c4_Bytes bin;
	bin = binfield(((*view)[pos]));

	const int len = bin.Size();
	if(len == 0) return _L8("");
	
	TPtrC8 ptr8((TUint8*)bin.Contents(), len);
	
	return ptr8;
}

const unsigned char* CMyDataCenter::FieldBinValue(c4_View* view, char* fieldname, int pos)
{
	c4_BytesProp binfield(fieldname);
	c4_Bytes bin;
	bin = binfield(((*view)[pos]));

	const int len = bin.Size();
	if(len == 0) return NULL;
	
	return bin.Contents();
}

int CMyDataCenter::FindByInt(c4_View* view, char* fieldname, int keyvalue)
{
	int pos = -1;
	c4_IntProp intfield(fieldname);
	pos = view->Find(intfield[keyvalue]);

	return pos;
}

int CMyDataCenter::FindBy2Int(c4_View* view, char* field1, int keyvalue1, char* field2, int keyvalue2)
{
	int pos = -1;
	c4_IntProp intfield1(field1);
	c4_IntProp intfield2(field2);	
	pos = view->Find(intfield1[keyvalue1]+intfield2[keyvalue2]);

	return pos;
}

int CMyDataCenter::FindByStr(c4_View* view, char* fieldname, char* keyvalue)
{
	int pos = -1;
	c4_StringProp strfield(fieldname);
	pos = view->Find(strfield[keyvalue]);

	return pos;
}

//prepare one image list for imagecontainer to display
//imgstart, to tell cotainer which to start
void CMyDataCenter::FakeImageList(int channel, int pageid, int imgamount)
{
	iImageList->Reset();
	
	TBuf<256> filename;
	for(int i = 0; i < imgamount; i++)
	{
		int imgindex = i + 1; //1-the first one
		filename.Format(KLocalImg, channel, pageid, imgindex);

//		if(ConeUtils::FileExists(filename))	
		{
			iImageList->AppendL(filename);
		}
	}
}

//从服务器端下载需要预览的小图片
//if the image is not exist on dist, return it's index to download from server
//1-the first image
int CMyDataCenter::FindImageToGet()
{
	//图片总数
	int imagenum = iPageInfo.imagenum;
	
	if(iImgDownTask.imgindex > imagenum)
	{
		iImgDownTask.imgindex = 0;
//		CEikonEnv::Static()->InfoMsg(_L("all images downloaded"));
		iWaitDlg.Note(_L("all images downloaded"),1);
		iDBInfo->Commit();
		return -1;
	}
	
	int imgindex = iImgDownTask.imgindex;		
	
	//当前页面信息
	int pageid = iPageInfo.pageid;
	int channel = iPageInfo.channelid;
	c4_View view = iDBInfo->View("pagelist");
	int find = FindByInt(&view, "pageid", pageid);
	if(find < 0)
		return -1;
		
	//下载	
	TBuf<128> info;
	info.Format(_L("%d/%d"), imgindex, imagenum);
//	AppUi()->ShowWaitDialog(&info);
	
	iImgDownTask.method = 1;
	iImgDownTask.pageid = pageid;
	iImgDownTask.channelid = channel;
	iImgDownTask.totalnum = imagenum;
	int subdir = pageid/500;
	
	TBuf8<256> url;
	url.Format(KRemotePreImg, channel, subdir, pageid, imgindex);
	
//			http://221.130.184.102/moimages/000/000001_01.jpg
//	url.Copy(_L("http://221.130.184.102/moimages/002/000037_01_m.jpg"));
	iAntiLock = iHistory->Count();
	IssueHTTPGetL(url, this);
	
	return 1;
}

void CMyDataCenter::HideMenu()
{
	iPopMenu.HideMenu();
}
	
void CMyDataCenter::InitBluetooth()
{
	if(!iBtMode)
	return;
	
////    iEngine->TurnBtOnL();	
////	if ( !iEngine->iIsSlave )
////        iEngine->myConnectDevice();    
    
}

void CMyDataCenter::LoadImageViewer(int imagestart)
{
	//
	iImageStart = imagestart;
	int pageid = iPageInfo.pageid;
	int channel = iPageInfo.channelid;
	int imgindex = 1; //the first image
	
	c4_View view = iDBInfo->View("pagelist");
	int find = FindByInt(&view, "pageid", pageid);
	if(find < 0)
		return;
		
	int imagesnum = FieldIntValue(&view, "images", find);
	
	FakeImageList(channel, pageid, imagesnum);
////	AppUi()->ActivateLocalViewL(TUid::Uid(EITestImageContainerViewId));
//		CEikonEnv::Static()->InfoWinL(_L("viewimage"), _L("here"));
}

//将已经下载到磁盘的预览图加载
/*
 * 当有很多小图片正在下载时，可能用户选了goback.
 * 下面加了一个防止死掉的代码,用ihistory判断 /2009.06.01
 */
void CMyDataCenter::LoadExistImages()
{
	int imgToShow = iHmPreview.NextImgToShow();
	if(	imgToShow == -1)//已经全部加载完
	return;

	MY_PREVIEW_DATA* data = iHmPreview.iSnapImgData[imgToShow];
	
	int pageid = iHmPreview.iPageId;
	int imgindex = data->imgid + 1;
	c4_View view2 = iDBInfo->View("pageimages");
	int find = FindBy2Int(&view2, "pageid", pageid, "orderid", imgindex);
	//if(ConeUtils::FileExists(filename))	
	if(find > -1)
	{
		//已确定有此图片在数据库里
		iHmPreview.SetSnapImg(imgToShow);
		gHtmlControl->RefreshAndDraw();	
		//try next one
		LoadExistImages();
	}
	else //如果不存在，开始从远程服务器下载
	{
		iImgDownTask.imgindex = imgindex;
		FindImageToGet();
	}
}

/*
 * 将类别显示在tab上
 * seltab 默认左边第1个是选中项
 */
void CMyDataCenter::FillNewsCataOnTab(int cid, int seltab)
{
	if(iCurrentCid == cid)
		return;
	else
		iCurrentCid = cid;
	
	iHmTab.ClearTabData();
	iHmTab.ShowTab();
	iHmUtil.AdjustClientHeight();

	c4_View view = gDBStore->View("channel");
	c4_IntProp pid("pid");
	c4_View subview = view.Select(pid[cid]);

	int count = subview.GetSize();	
	for(int i = 0; i < count; i++)
	{
		MY_TAB_DATA* data = new MY_TAB_DATA;
		data->cid = FieldIntValue(&subview, "cid", i);
		data->level = FieldIntValue(&subview, "level", i);
		data->freshtime = 0;		
				
		TPtrC ptr = FieldUnicodeValue(&subview, "name", i);
		data->tabtitle.Copy(ptr);
		
		iHmTab.iAppTabData.Append(data);
	}

	iHmTab.Init(gHtmlControl, 3, seltab);	
	gHtmlControl->RefreshAndDraw();	
}

void CMyDataCenter::FillNewsItemOnList(int cid)
{
	CHtmlElement* divContent = gHtmlControl->Element(_L("iContent"),0);
	if(divContent == NULL) return;
	divContent->SetProperty(KHStrInnerHtml, KNullDesC);

	if(cid >= 1000){
		News_List(cid, 0);
		return;
	}

	//站点
	c4_View view = gDBStore->View("channel");

	c4_IntProp pid("pid");
	
	c4_View subview = view.Select(pid[cid]);
	int size = subview.GetSize();

//Use DIV as container.	
_LIT(KHtml2, "<div id='list' style='width:100%;height:auto;overflow:auto'></div>");

gHtmlControl->InsertContentL(divContent, EBeforeEnd, KHtml2);
CHtmlElement* list = gHtmlControl->Element(_L("list"));

//Set list item template.

_LIT(KItemHtml, 
"<div id='listitem' style='width:100%; height:22;' focusing='true' class='listitem' focus-class='listfocus'>"
        "<div id='title' style='padding:auto 0 auto 2; width:auto; height:100%' line-wrap='scroll'></div>"
        "<div id='link' style='display:none'></div>"        
"</div>");

	TBuf<100> buf;
	/*
	 * 由于左右键时通过SyncrosizeActiveTab去检查top category的更新
	 * 下列的link赋值语句失去作用,以后要删除 2009.05.28
	 */
	 
	for(TInt i=0; i < size; i++)
	{
		if(i!=0)
			gHtmlControl->InsertContentL(divContent, EBeforeEnd, _L("<br/>"));
			
		CHtmlElement* cat = gHtmlControl->InsertContentL(list, EBeforeEnd, KItemHtml);

		CHtmlElement* title = cat->Element(_L("title"));
		CHtmlElement* link = cat->Element(_L("link"));		
		
		TPtrC ptr = FieldUnicodeValue(&subview, "name", i);
		title->SetProperty(KHStrInnerText, ptr);
		
		TBuf<256> linkstr;
		int cid = FieldIntValue(&subview, "cid", i);
		linkstr.Format(_L("self?pfunc_sitelist(%d)"), cid);//用self不会被记录到history中
//		linkstr.Format(_L("news/index_site.xml?pfunc_sitelist(%d)"), cid);
		link->SetProperty(KHStrInnerText, linkstr);		
		//CHtmlElement* content = gHtmlControl->AppendContentL(KCatContentHtml);
	
	}
	

//

	
	gHtmlControl->RefreshAndDraw();
}
	

//如果当前的newslist 检查当前Tab上的的channel或者category是否有更新
void CMyDataCenter::SyncrosizeActiveTab()
{
	if(iHttpPosting)
	return;
	
	if(iHmTab.iTabNum == 0)
	return;

	iTimer->Cancel();
	iTimer->Activate();
}

void CMyDataCenter::SyncrosizeActiveTab2()
{	
	int index = iHmTab.GetActiveTabIndex();
	MY_TAB_DATA* data = iHmTab.iAppTabData[index];	
	
	TBuf<10> bb;
	bb.Num(data->cid);
	CEikonEnv::Static()->InfoMsg(bb);
	if( (Dateline() - data->freshtime) > 120)//先把第１道关
	{
		TBuf<128> poststr;
		if(data->level < 3)
		{
			c4_View category = gDBStore->View("channel");
			int find = FindByInt(&category, "cid", data->cid);
			
			int dateline = Dateline();			
			int checktime = FieldIntValue(&category, "checktime", find);			
			
			int updatetime = 0;
			if(find >= 0) updatetime = FieldIntValue(&category, "update", find);
			
			bool check = (checktime > dateline)||((dateline - checktime) > CategoryCheckTime); //86400			
			if (check)//超过１天就去检查更新,否则每个goback都会去check
			{
				iWaitDlg.Note(_L("Check updating of category..."));							
				//注明本类的检查时间
				SetRowRefIntValue(category[find], "checktime", dateline);
				
				poststr.Format(_L("post?news_checkcategory(%d,%d)"), data->cid, updatetime);
				Post(poststr);
			}
		}
		else if(data->level == 3)
		{
			iWaitDlg.Note(_L("Check updating of news..."));						
			poststr.Format(_L("post?news_checklist(%d)"), data->cid);		
			Post(poststr);
		}
		data->freshtime = Dateline();
	}	
}

/*
 * 
 * 目前仅处理图片下载
 */
void CMyDataCenter::IssueHTTPGetL(const TDesC8& aUri, MClientObserver* aObserver)
{
	if(iBtMode)
	{
////		iEngine->SetCaller(this, iHttpImgDown->iClientID);
////		iEngine->SendData(aUri);
		return;
	}
	else
	{
		MClientObserver* Observer = aObserver;
		if(Observer == NULL) Observer = this;
		iImgDownloading = true;
		iHttpImgDown->IssueHTTPGetL(aUri, Observer);
	}
	
}

void CMyDataCenter::IssueHTTPPostL(const TDesC8& aUri,
						const TDesC8& aContentType,
						const TDesC8& aBody, MClientObserver* aObserver)
{
	if(iBtMode)
	{
////		iEngine->SetCaller(this, iHttpEngine->iClientID);
////		HBufC8* ibuf = HBufC8::NewLC(aUri.Length() + aBody.Length() + 2);
////		ibuf->Des().Copy(aUri);
////		ibuf->Des().Append(_L8("\r\n"));
////		ibuf->Des().Append(aBody);
////		iEngine->SendData(*ibuf);
////			
////		CleanupStack::PopAndDestroy(ibuf);				
	}
	else
	{
		iHttpPosting = true;
		MClientObserver* Observer = aObserver;
		if(Observer == NULL) Observer = this;
		iHttpEngine->IssueHTTPPostL(aUri, aContentType, aBody, Observer);
	}
}

//get xmlfile name from an string
//e.g, if the str is "test/demo/index.xml?myfunc(x1,x2)
//the result is "test/demo/index.xml"
TPtrC getxmlname(const TDesC& paras)
{
	int len = paras.Length();	
	int pos = paras.Find(_L(".htm"));	

	if(pos == KErrNotFound){
		return paras;
	}
	else 
		return paras.Left(pos + 4);
}

bool CMyDataCenter::IsMenuVisible()
{
	return true;
	//return iPopMenu->IsVisible();
}

//从资源数据库里读出图片数据
bool CMyDataCenter::LoadPageImage(CImageHandler* aImageHandler, const TDesC& aFileName, int aSelectedFrame)
{
	c4_View view = iDBRes->View("image");
	
	TBuf8<256> str8;
	str8.Copy(aFileName);
	char* path = (char *)str8.Ptr();
	path[aFileName.Length()] = 0;
	
	int find = FindByStr(&view, "path", path);
	if(find < 0)
		return false;

	TPtrC8 ptr = FieldUtf8Value(&view, "data", find);
	aImageHandler->LoadBuffer(&ptr, aSelectedFrame);
		
	return true;	
}	

//only support english name
void CMyDataCenter::LoadMemPage(char* resname, const TDesC& path, bool addhistory)
{
	iHttpImgDown->CancelTransaction();
	iHmTab.HideTab();
	iHmUtil.AdjustClientHeight();	


	if(path.Find(_L("self?")) == 0)
	{
		ProcessPageParameters(path);
		return;
	}
	else
	{
		;//if(aREdit == iEditor)
		//	AppUi()->RemoveAllTabGroupItem();
	}

	TPtrC pagename = getxmlname(path);	

	if(addhistory)
	{
//		CEikonEnv::Static()->InfoMsg(_L("add history"));
		//if(aREdit == iEditor)
		AddHistory(path);	
	}


	if(pagename == _L(""))
	return;
	//hide any popuped menu
	//if(aREdit != iMnuEditor)
	HideMenu();

	{
		c4_View vp = gDBStore->View(resname);

		char* szpagename = new char[pagename.Length()+1];
		szpagename[pagename.Length()] = 0;		
		for(int i = 0; i < pagename.Length(); i++)
			szpagename[i] = pagename[i];
					
	c4_StringProp s1 ("name");
	c4_Row row;
	c4_String str(szpagename); delete szpagename;
    s1(row) = str; //"login.xml";
	int find = vp.Find(row);
	if(find == -1) find = 0;

	//	if(aREdit == iEditor)
	const TPtrC8 menustr = FieldStr8Value(&vp, "menu", find);
	
	iMenuStr.Copy(menustr);

	    c4_BytesProp p2 ("content");
		c4_Bytes bin2 = p2(vp[find]);
	
		TUint8 * buf = new TUint8[bin2.Size()];
		memcpy(buf, bin2.Contents(), bin2.Size());
		TPtrC8 ptr2(buf, bin2.Size());
		
		//TPtrC ptrr = FieldUnicodeValue(&vp, "content", find);

		if(path.Find(_L(".htm")) != KErrNotFound && gHtmlControl)
		{
			gHtmlControl->MakeVisible(true);			
		
			HBufC* pageData = CnvUtfConverter::ConvertToUnicodeFromUtf8L(ptr2);
			CleanupStack::PushL(pageData);

			CHtmlElement* pageContainer = gHtmlControl->Element(_L("iContent"));
			if(pageContainer)
				pageContainer->SetProperty(KHStrInnerHtml, KNullDesC);

			//gHtmlControl->ClearContent();
			
			//CEikonEnv::Static()->InfoWinL(_L("test"), _L("tes"));
			//gHtmlControl->AppendContentL(*pageData);
			if(pageContainer)
				pageContainer->SetProperty(KHStrInnerHtml, *pageData);
			else
				gHtmlControl->AppendContentL(*pageData);
			
			gHtmlControl->RefreshAndDraw();

			CleanupStack::PopAndDestroy(pageData); // pageData		

		}
		else
		{
			CEikonEnv::Static()->InfoWinL(_L("test"), _L("can not load xml now"));
		}
		delete buf;
	}

	//finally
	iHmGridView.ParsePage(gHtmlControl);
	//default
	ProcessPageParameters(path);
}

void CMyDataCenter::Login(const TDesC8& PostTemplate)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;	
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();
		
    iBtMode = false;	
    
	TBuf<32> buf1;			
	gHtmlControl->Element(_L("username"))->GetProperty(KHStrValue, buf1);
	
	TBuf<32> buf2;			
	gHtmlControl->Element(_L("password"))->GetProperty(KHStrValue, buf2);

	TBuf8<32> user;
	user.Copy(buf1);
	TBuf8<32> pwd;
	pwd.Copy(buf2);
	
	ptr8.Format(PostTemplate, &user, &pwd);

//	IssueHTTPPostL(KTestIP, _L8("*.*"), ptr8, this);				
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
	
	CleanupStack::PopAndDestroy(iBuf8);
	
	c4_View view = gDBStore->View("general");
	SetRowRefStrValue(view[0], "username", buf1);

////	LoadMemPage("syspage", _L("index.htm"),false);	
}

void CMyDataCenter::Mail_ReadConfig()
{
	c4_View view = iDBMail->View("account");
	int size = view.GetSize();
	if(size == 0)
	return;
	
////	const TPtrC mailaddress = FieldStrValue(&view, "mailaddress", 0);
////	iEditor->SetEditValue(_L("account"), mailaddress);	
////	const TPtrC password = FieldStrValue(&view, "password", 0);	
////	iEditor->SetEditValue(_L("password"), password);		

////	iEditor->TextView()->HandleGlobalChangeL();				
}

void CMyDataCenter::MailCheckList(const TDesC8& PostTemplate)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;
	
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();
	
	TBuf8<64> userid8;
	userid8.Copy(iUserid);

	TBuf8<64> maid8;
	maid8.Copy(iMAccountid);

	int lastmessageid = 0;
	
	c4_View v = iDBMail->View("inbox");
	int size = v.GetSize();
	if(size > 0)
	{	
		lastmessageid = FieldIntValue(&v, "messageid", size-1);
	}
	
	iWaitDlg.Note(_L("Checking mail list..."));	
	
	///userid8.Copy(_L8("1"));//for test
	ptr8.Format(PostTemplate, &userid8, &maid8, lastmessageid);
	
//	IssueHTTPPostL(KTestIP, _L8("*.*"), ptr8, this);				
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	

	CleanupStack::PopAndDestroy(iBuf8);				
}

void CMyDataCenter::MailContentRead(const TDesC8& PostTemplate, const TDesC& szLocalId)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;
	
	TBuf8<128> userid8;
	userid8.Copy(iUserid);
	///userid8.Copy(_L8("1"));//for test
				
	int localid = 0;
	TLex lex(szLocalId);
	lex.Val(localid);

	//CEikonEnv::Static()->InfoWinL(_L("test"), _L("here1"));
	c4_View v = iDBMail->View("inbox");
	int find = FindByInt(&v, "id", localid);
	if(find < 0) return;

	int messageid = FieldIntValue(&v, "messageid", find);

	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();

	ptr8.Format(PostTemplate, localid, &userid8, messageid);
	//CEikonEnv::Static()->InfoWinL(_L("test"), _L("here"));
	//_LIT8(KTestIP, "http://127.0.0.1:8081/");
	//IssueHTTPPostL(KTestIP, _L8("*.*"), ptr8, this);				
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
	
	CleanupStack::PopAndDestroy(iBuf8);				
	
}

void CMyDataCenter::MailReply(const TDesC8& PostTemplate)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;

	//step1	
	TBuf<256> subject;
	TBuf<256> fromaddr;
	gHtmlControl->Element(_L("subject"))->GetProperty(KHStrInnerText, subject);
	gHtmlControl->Element(_L("fromaddr"))->GetProperty(KHStrInnerText, fromaddr);	
	TInt bufSize;
	
	_LIT(KIdA1, "message");
	
	gHtmlControl->Element(KIdA1)->GetProperty(KHStrBufSize, bufSize);
	HBufC* hbuf = HBufC::NewLC(bufSize);
	TPtr ptr = hbuf->Des();
	gHtmlControl->Element(KIdA1)->GetProperty(KHStrInnerText, ptr);

	//step2
	LoadMemPage("syspage", _L("mail/send.htm"),false);
	_LIT(KIdA3, "subject");
	TBuf<256> subject2;
	subject2.Copy(_L("Re:"));
	subject2.Append(subject);
	gHtmlControl->Element(KIdA3)->SetProperty(KHStrValue, subject2);
	gHtmlControl->Element(_L("to"))->SetProperty(KHStrValue, fromaddr);	

	gHtmlControl->Element(_L("msgbody"))->SetProperty(KHStrValue, ptr);	
	
	CleanupStack::PopAndDestroy();	
	gHtmlControl->RefreshAndDraw();			
/*
	//CEikonEnv::Static()->InfoWinL(_L("test"), _L("here1"));
	c4_View v = iDBMail->View("inbox");
	int find = FindByInt(&v, "id", localid);
	if(find < 0) return;

	int messageid = FieldIntValue(&v, "messageid", find);

	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();

	ptr8.Format(PostTemplate, localid, &userid8, messageid);
	//CEikonEnv::Static()->InfoWinL(_L("test"), _L("here"));
	//_LIT8(KTestIP, "http://127.0.0.1:8081/");
	//IssueHTTPPostL(KTestIP, _L8("*.*"), ptr8, this);				
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
	
	CleanupStack::PopAndDestroy(iBuf8);				
*/	
	//
//	LoadMemPage("syspage", _L("mail/send.htm"),false);	
	//MailSend(ptrc8);			
	
	
}

void CMyDataCenter::MailSend(const TDesC8& PostTemplate)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;
	
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();
		
	TBuf<200> mailto;
	TBuf<200> subject;	
	int bufSize;
	
	_LIT(KIdA1, "to");
	gHtmlControl->Element(KIdA1)->GetProperty(KHStrValue, mailto);

	_LIT(KIdA3, "subject");
	gHtmlControl->Element(KIdA3)->GetProperty(KHStrValue, subject);
	
	_LIT(KIdA2, "msgbody");
	gHtmlControl->Element(KIdA2)->GetProperty(KHStrBufSize, bufSize);
	HBufC* mailbody = HBufC::NewLC(bufSize);
	TPtr ptr = mailbody->Des();
	gHtmlControl->Element(KIdA2)->GetProperty(KHStrValue, ptr);
				
			TBuf8<128> mailto8;
			mailto8.Copy(mailto);
			TBuf8<64> userid8;
			userid8.Copy(iUserid);
			TBuf8<64> maid8;
			maid8.Copy(iMAccountid);
			
			///userid8.Copy(_L8("1"));//for test			

			MyUnicode2Utf8 subjectutf8(subject);
			MyUnicode2Utf8 mailbodyutf8(*mailbody);			
////CEikonEnv::Static()->InfoWinL(_L("KIdA1"), *mailbody);
			ptr8.Format(PostTemplate, &userid8, &maid8, &mailto8, &(subjectutf8.Ptr8()), &(mailbodyutf8.Ptr8()));
////			ptr8.Format(PostTemplate, &userid8, &mailto8, &userid8, &userid8);
			//_LIT8(KTestIP, "http://127.0.0.1:8081/");
			//IssueHTTPPostL(KTestIP, _L8("*.*"), ptr8, this);							
////CEikonEnv::Static()->InfoWinL(_L("KIdA2"), *mailbody);
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
			
	CleanupStack::PopAndDestroy();
	CleanupStack::PopAndDestroy(iBuf8);				
	
}

void CMyDataCenter::Mail_List(int indicator)
{
_LIT(KIdList, "list"); 
iList = gHtmlControl->Element(KIdList); 
iList->InvokeL(KHStrCreateList, (MListItemRenderer*)this); 

//设置列表项模板 
_LIT(KListItemHtml,  
  "<div id='mail_listitem' style='width:100%; height:42;' class='list_item' focus-class='list_focus-item'>" 
      "<div style='width:20;height:100%;border-right:1 dotted;padding:auto auto'><img src='' width='14' height='14'></div>"
	  "<div id='right' style='padding:auto 0 auto 2; width:auto; height:100%' line-wrap='scroll'>"
		"<div id='from' style='width:100%; height:21'>from</div>"
		"<div id='title' style='width:100%;height:21'>title</div>"		
	  "</div>"
	  "<div id='link' style='display:none'>link</div>"
  "</div>"); 
iList->SetProperty(KHStrListItemHtml, KListItemHtml);   
 
//设置当列表为空时显示的内容 
_LIT(KEmptyHtml, "<p align='center'>(No Mail)</p>"); 
iList->SetProperty(KHStrListEmptyHtml, KEmptyHtml); 
 
//设置列表项目数量 
iList->SetProperty(KHStrListItemCount, 20); 
	
//更新并重画控件 
gHtmlControl->RefreshAndDraw();	

return;
	CHtmlElement* divContent = gHtmlControl->Element(_L("iContent"),0);
	if(divContent == NULL) return;
	divContent->SetProperty(KHStrInnerHtml, KNullDesC);
	
//Use DIV as container.	
_LIT(KHtml2, "<div id='list' style='width:100%;height:auto;overflow:auto'></div>");
gHtmlControl->InsertContentL(divContent, EBeforeEnd, KHtml2);
CHtmlElement* list = gHtmlControl->Element(_L("list"));
list->SetProperty(KHStrScrollLoop, ETrue);

//Set list item template.
_LIT(KItemHtml, 
"<div id='listitem' style='width:100%; height:42;' focusing='true' class='listitem' focus-class='focus'>"
        "<div id='title' style='padding:auto 0 auto 2; width:auto; height:50%' line-wrap='scroll'></div>"
        "<div id='from' style='padding:auto 0 auto 2; width:auto; height:50%' line-wrap='scroll'></div>"
        "<div id='link' style='visible:none'></div>"        
"</div>");


	if(indicator == 0)
		m_pageIntVar = 0;

	c4_View view = iDBMail->View("inbox");
	int size = view.GetSize();
	
	int offset = 5;
	if(indicator == 1 && m_pageIntVar < size - 1)
	{
		m_pageIntVar += offset;
	}	
	else if(indicator == -1 && m_pageIntVar > 0)
		m_pageIntVar -= offset;
		
	int from = m_pageIntVar;

	int count = 0;

	int index = 1;
	/*
	 * 这里有一个bug,size太大时内存不足...
	 */
	if(size > 100) size = 30;
	
	for(int i = size - 1 - from; i >= 0; i--)
	{
		int localid = FieldIntValue(&view, "id", i);
		TPtrC ptr = FieldUnicodeValue(&view, "subject", i);
		if(ptr == _L("")) continue;
		
		
		const TPtrC8 fromaddr8 = FieldStr8Value(&view, "fromaddr", i);
		MyStr16 fromaddr(fromaddr8);

		
		TBuf<256> linkstr;
		linkstr.Format(_L("mail/readmail.htm?pfunc_readmail(%d)"), localid);
		
		CHtmlElement* cat = gHtmlControl->InsertContentL(list, EBeforeEnd, KItemHtml);
		CHtmlElement* title = cat->Element(_L("title"));
		CHtmlElement* from = cat->Element(_L("from"));		
		CHtmlElement* link = cat->Element(_L("link"));				
			
		TBuf<256> szTitle;
		szTitle.Format(_L("%d %S"), index++, &ptr);
		title->SetProperty(KHStrInnerText, szTitle);//ptr);
		from->SetProperty(KHStrInnerText, fromaddr.Value());
		link->SetProperty(KHStrInnerText, linkstr);	
				
		count ++;
//		if(count == offset)
//			break;
	}
			
}

void CMyDataCenter::Mail_ReadMsg(int localid)
{
	c4_View view = iDBMail->View("inbox");
	int find = FindByInt(&view, "id", localid);
	if(find < 0) return;

	CHtmlElement* divContent = gHtmlControl->Element(_L("iContent"),0);
	TPtrC from = FieldUnicodeValue(&view, "from", find);
	CHtmlElement* fromfield = divContent->Element(_L("from"));		
	fromfield->SetProperty(KHStrInnerText, from);
	
	const TPtrC8 fromaddr8 = FieldStr8Value(&view, "fromaddr", find);
	MyStr16 fromaddr(fromaddr8);
	
	CHtmlElement* fromaddrfield = divContent->Element(_L("fromaddr"));		
	fromaddrfield->SetProperty(KHStrInnerText, fromaddr.Value());

	TPtrC ptr = FieldUnicodeValue(&view, "subject", find);
	CHtmlElement* subjectctrl = divContent->Element(_L("subject"));		
	subjectctrl->SetProperty(KHStrInnerText, ptr);

	TPtrC ptr2 = FieldUnicodeValue(&view, "content", find);

	int done = FieldIntValue(&view, "done", find);
	if(done == 0)
	{
		TBuf<128> buf;
		buf.Format(_L("post?mail_readcontent(%d)"), localid);
		iWaitDlg.Note(_L("Getting mail content..."));
		Post(buf);
		//CEikonEnv::Static()->InfoWinL(_L("test"), buf);
	}else{
		CHtmlElement* messagectrl = divContent->Element(_L("message"));		
		messagectrl->SetProperty(KHStrInnerText, ptr2);
	}
	gHtmlControl->RefreshAndDraw();

}

/*
 * 改变应用的Tab位置
 */
void CMyDataCenter::NextPrevAppTab()
{
//	iWaitDlg->Note(_L("test"));
	if(iHmTab.iAppTabData.Count() == 0)
	return;
	
	int index = iHmTab.GetActiveTabIndex();
	MY_TAB_DATA* data = iHmTab.iAppTabData[index];
	int cid = data->cid;
//	TBuf<100> buf;
//	buf.Num(cid);
//	CEikonEnv::Static()->InfoWinL(_L("test"), buf);	

	FillNewsItemOnList(cid);
	
	//为了返回时能回到正确的active tabindex,修改当前历史url的参数
	{
	TBuf<128> para;
	para.Format(_L("(%d,%d)"), iCurrentCid, index);//icurrentcid is top cid
	ChangeCurrentHistoryPara(para);
	}
	
	//检查当前选中tab项下的子类或者新闻条目是否有更新
////	TBuf<100> buf;
////	buf.Num(cid);
////	CEikonEnv::Static()->InfoWinL(_L("test"), buf);
	SyncrosizeActiveTab();	
}

void CMyDataCenter::NewsContentRead(const TDesC8& PostTemplate, int pageid)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;
	
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();
	
	ptr8.Format(PostTemplate, pageid);
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
	
	CleanupStack::PopAndDestroy(iBuf8);					
}

void CMyDataCenter::NewsCategoryCheck(const TDesC8& PostTemplate, const TDesC& szCid, const TDesC& szUpdateTime)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;
	
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();
	
	TBuf8<128> cid;
	cid.Copy(szCid);
	TBuf8<128> updatetime;
	updatetime.Copy(szUpdateTime);
	
	c4_View temp = iDBTemp->View("category");
	temp.RemoveAll();
	
	ptr8.Format(PostTemplate, &cid, &updatetime);
	//_LIT8(KTestIP, "http://127.0.0.1:8081/");	
	//IssueHTTPPostL(KTestIP, _L8("*.*"), ptr8, this);
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
	
	CleanupStack::PopAndDestroy(iBuf8);		
}

void CMyDataCenter::NewsListCheck(const TDesC8& PostTemplate, int channelid)
{
	int len = PostTemplate.Length();	
	if(len == 0)
	return;
	
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();
		
	c4_View temp = iDBTemp->View("category");
	temp.RemoveAll();
	
	int lasttimestamp = 0;
	
	c4_View v = iDBInfo->View("pagelist");
	c4_IntProp channelprop("channelid");
	c4_View subview = v.Select(channelprop[channelid]);
	int size = subview.GetSize();
	if(size > 0)
	{	
		lasttimestamp = FieldIntValue(&subview, "timestamp", size-1);
	}
	
//			CEikonEnv::Static()->InfoMsg(_L("check_newslist"));
//			AppUi()->ExecuteWaitDialog1LD(NULL);
	
	ptr8.Format(PostTemplate, channelid, lasttimestamp);
	IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
	
	CleanupStack::PopAndDestroy(iBuf8);				
}

void CMyDataCenter::News_List(int channelid, int batchid)
{
	CHtmlElement* divContent = gHtmlControl->Element(_L("iContent"),0);	
	if(divContent == NULL) return;
		divContent->SetProperty(KHStrInnerHtml, KNullDesC);
	
//Use DIV as container.	
//_LIT(KHtml2, "<div id='list' style='width:100%;height:auto;'></div>");
_LIT(KHtml2, "<div id='list' style='width:100%;height:auto;overflow:auto'></div>");

gHtmlControl->InsertContentL(divContent, EBeforeEnd, KHtml2);
CHtmlElement* list = gHtmlControl->Element(_L("list"));
list->SetProperty(KHStrScrollLoop, ETrue);

//Set list item template.
_LIT(KItemHtml, 
"<div id='listitem' style='width:100%; height:22;' focusing='true' class='listitem' focus-class='listfocus'>"
		"<div id='icon'></div>"
        "<div id='title' style='padding:auto 0 auto 2; width:auto; height:100%' line-wrap='scroll'></div>"
        "<div id='link' style='visible:none'></div>"        
"</div>");

/*
for(int i = 0; i <10; i++)
{
	TBuf<100> desc;
	desc.Format(_L("channelid %d"), channelid);
	CHtmlElement* cat = gHtmlControl->InsertContentL(list, EBeforeEnd, KItemHtml);
	CHtmlElement* title = cat->Element(_L("title"));
	CHtmlElement* link = cat->Element(_L("link"));		
		
	title->SetProperty(KHStrInnerText, desc);
	link->SetProperty(KHStrInnerText, _L("linkstr"));
}
*/
	iPageInfo.channelid = channelid;

	c4_View view = iDBInfo->View("pagelist");

	c4_IntProp channelprop("channelid");

	c4_View subview = view.Select(channelprop[channelid]);
	int size = subview.GetSize();


	int itemsinpage = 15;
	int pagenum = (size-1) / itemsinpage + 1;	
		
	int from = itemsinpage * batchid;
	//stage 1, make a xml buffer

	int count = 0;

	//for next/prev indicator
	if(batchid != 0)
	{	
		TBuf<128> desc;
		desc.Format(_L("Page %d/%d, Prev Page"), batchid+1, pagenum);

		TBuf<256> linkstr;
		int id = batchid - 1;
		linkstr.Format(_L("self?pfunc_newslist(%d,%d)"), channelid, id);
		
		CHtmlElement* cat = gHtmlControl->InsertContentL(list, EBeforeEnd, KItemHtml);
		CHtmlElement* title = cat->Element(_L("title"));
		CHtmlElement* link = cat->Element(_L("link"));		
		
		title->SetProperty(KHStrInnerText, desc);
		link->SetProperty(KHStrInnerText, linkstr);				
	}

	for(int i = size - 1 - from; i >= 0; i--)
	{
		int pageid = FieldIntValue(&subview, "pageid", i);
		int imagesnum = FieldIntValue(&subview, "images", i);
	
		TPtrC ptr = FieldUnicodeValue(&subview, "title", i);

		TBuf<100> iconstr;		
		TBuf<256> linkstr;
		if(imagesnum > 0){
			iconstr.Copy(_L("<img src=mem.news_img.gif>"));
			linkstr.Format(_L("news/readnews2.htm?pfunc_readnews(%d)"), pageid);
		}
		else{
			iconstr.Copy(_L("<img src=mem.news_txt.gif>"));		
			linkstr.Format(_L("news/readnews.htm?pfunc_readnews(%d)"), pageid);
		}
			
		CHtmlElement* cat = gHtmlControl->InsertContentL(list, EBeforeEnd, KItemHtml);
		CHtmlElement* icon = cat->Element(_L("icon"));		
		CHtmlElement* title = cat->Element(_L("title"));
		CHtmlElement* link = cat->Element(_L("link"));		
			
		title->SetProperty(KHStrInnerText, ptr);
		link->SetProperty(KHStrInnerText, linkstr);				
		icon->SetProperty(KHStrInnerHtml, iconstr);		
		
		count ++;
		if(count == itemsinpage)
			break;
	}

	if(batchid < pagenum - 1)
	{	
		TBuf<128> desc;
		desc.Format(_L("Page %d/%d, Next Page"), batchid+1, pagenum);

		TBuf<256> linkstr;
		int id = batchid + 1;
		linkstr.Format(_L("self?pfunc_newslist(%d,%d)"), channelid, id);

		CHtmlElement* cat = gHtmlControl->InsertContentL(list, EBeforeEnd, KItemHtml);
		CHtmlElement* title = cat->Element(_L("title"));
		CHtmlElement* link = cat->Element(_L("link"));		
			
		title->SetProperty(KHStrInnerText, desc);
		link->SetProperty(KHStrInnerText, linkstr);				
	}

	gHtmlControl->RefreshAndDraw();	
	//uniqueid, 只要区别于其它就可以了
////	SetTabWithChannel(100+siteid, siteid); 
}

void CMyDataCenter::News_ReadMsg(int pageid)
{
	//强迫下次出现apptab
	iTabGroupUid = -1;
//	iCurrentCid = -1;
	
	iPageInfo.pageid = pageid;
	
	c4_View view = iDBInfo->View("pagelist");
	int find = FindByInt(&view, "pageid", pageid);
	if(find < 0) return;
	
	int imagenum = FieldIntValue(&view, "images", find);
	iPageInfo.imagenum = imagenum;
	
	int done = FieldIntValue(&view, "pagedone", find);
	if(done == 1 )
	{	
		if(imagenum > 0){
			iHmPreview.ClearSnapData();
			int channelid = iPageInfo.channelid;
			iHmPreview.Init(gHtmlControl, imagenum, pageid, channelid);
		}

		TPtrC content = FieldUnicodeValue(&view, "content", find, true);
		CHtmlElement* divContent = gHtmlControl->Element(_L("newscontent"),0);
		////divContent->SetProperty(KHStrScrollLoop, ETrue);
		if(divContent == NULL) return;
		divContent->SetProperty(KHStrInnerText, content);
		gHtmlControl->RefreshAndDraw();
	}
	else if(done == 0)
	{
		TBuf<128> buf;
		buf.Format(_L("post?news_readcontent(%d)"), pageid);
		Post(buf);
	}
}

void CMyDataCenter::ParseXMLBuffer(const TDesC8& aBuffer, MSyDocHandler* aDocHandler)
{
	// 2. Create the XML Parser	and set the default document handlers
	CSyParser*   reader = CSyParser::NewLC(TPtrC());		

//	RTest test(_L("XML String"));
//	CFeedbackHandler feedbackHandler(test);
	reader->SetHandler(aDocHandler);

	// 3. We set up the buffer with a default size of 128 bytes.
	//    This buffer is set purposly small so that we execute the
	//    parse stuff as often as possible to show aynchronous parsing
	//    We alse set up some loop variables
	const int KMaxBufLen = 128;
	TBuf8<KMaxBufLen> buf;
	TBool isFinal = ETrue;
	TSyExpatStatus status = EStatusOk;
		
	int LenToRead = aBuffer.Length();
	long cursor = 0;
	Byte* bufptr = (Byte*)aBuffer.Ptr();	
	do
	{
		// 4. First read some data
		//    Note that if there was an error reading there
		//    data an error will be returned, this is not the
		//    case with eof where the buffer will be smaller than
		//    maxBufLen.
		int len = KMaxBufLen;
		if(LenToRead < KMaxBufLen)
			len = LenToRead;
			
		buf.Copy(bufptr, len);
		bufptr += KMaxBufLen;
		LenToRead -= KMaxBufLen;

		// 5. Next we attempt to parse the result buffer
		//    or if we reached the end of the file the 
		//    partial buffer
		isFinal = (LenToRead <= 0);
					
		status = reader->Parse(buf, isFinal);
		// 6. When the parser returns an error
		//    we log it 
		//    Otherwise if there is no more data
		//    then we report we have finished
		if (status != EStatusOk)
		{
			_LIT(KError,"Error on Line %d Column %d\n");
			CEikonEnv::Static()->InfoMsg(KError);
			///test.Printf(KError, reader->GetCurrentLineNumber(), reader->GetCurrentColumnNumber());
		}
		else
		{
			if (isFinal)
			{
				_LIT(KFinished, "Finished parsing file\n");
//				CEikonEnv::Static()->InfoMsg(KFinished);
				///test.Printf(KFinished);
			}
		}
		
		// 7. finally we see if we have to loop round
		//    any more - we stop if we find an error or
		//    we have reached the end of the file
	} while (status == EStatusOk && !isFinal);		

	// 8.  Finally delete the parser
	CleanupStack::PopAndDestroy(1);
}

void CMyDataCenter::ParseRemoteFeedback(const CFeedbackHandler* feedback)
{
	if(!feedback->iDataBuffer[data_func]){
		iWaitDlg.EndWait();
		return;
	}
		

	int commandid = CommandIndex(feedback->iDataBuffer[data_func]->Des());

	switch(commandid)
	{
		case task_error:
		{
			iWaitDlg.EndWait();
			CEikonEnv::Static()->InfoWinL(_L("error"), *(feedback->iDataBuffer[data_desc]));
		}
		break;
		
		case task_login2:
		case task_login_bt:
		{
			LoadMemPage("syspage", _L("index.htm"));
			//return;
			{			
				c4_View temp = iDBTemp->View("login");

				//duplicate userinfo
				c4_View vuser = iDBTemp->View("user");				
				c4_View vuser2 = gDBStore->View("login");
				vuser2.RemoveAll();
				vuser2.Add(vuser[0]);
				
				if(temp.GetSize() == 0)
				{
					iWaitDlg.Note(_L("login fail"), 2);
					break;
				}
				
				const TPtrC8 userid8 = FieldStr8Value(&temp, "userid", 0);
				iUserid.Copy(userid8);
				
				const TPtrC8 maid8 = FieldStr8Value(&temp, "accountid", 0);
				iMAccountid.Copy(maid8);
				//temp.RemoveAll();,不用删除这个临时表，因为后面会多次引用
				TPtrC desc = FieldUnicodeValue(&temp, "desc", 0);
				iWaitDlg.Note(desc, 3);
			}
			
			{			
			c4_View temp = iDBTemp->View("software");
			c4_View temp2 = gDBStore->View("general");
			
			int version = FieldIntValue(&temp, "version", 0);
			int myver = FieldIntValue(&temp2, "version", 0);

			if(version == myver || version == 0)//后者是服务器没有返回
			{
				;//iWaitDlg.Note(_L("It's the latest software"), 1);
			}
			//虽然有更新，但无需强制更新下载
			else if((version - myver) < 10)
			{
				iWaitDlg.Note(_L("Found optional updated version"), 1);				
				LoadMemPage("syspage", _L("update.htm?update"));
			}
			else
			{
				iWaitDlg.Note(_L("Must updated your software"), 1);
				LoadMemPage("syspage", _L("update2.htm?update"));
				iHistory->Reset();				
			}
			
			temp.RemoveAll();
			}
			
			///iEditor->ReplaceMyField(_L("user"), iUsername);
			///iEditor->TextView()->HandleGlobalChangeL();
			
			//一些初始化工作
			//检查远程邮件帐号
			//专业版里提供多个帐号,itest里只提供一个
//			Post(_L("post?mail_listaccount"));	
			
		}
		break;

		case mail_check_list:
		{
			CEikonEnv::Static()->InfoWinL(_L("test"), _L("got check mail list"));	
			iDBMail->Commit();
//			AppUi()->RemoveWaitDialog1L();
			if(feedback->iDataBuffer[data_desc])
				iWaitDlg.Note(feedback->iDataBuffer[data_desc]->Des(), 1);
		}
		break;

		case mail_check_list2:
		{
//			CEikonEnv::Static()->InfoWinL(_L("test"), _L("got check mail list"));	
//			iDBMail->Commit();
//			AppUi()->RemoveWaitDialog1L();
			iWaitDlg.Note(_L("got check mail list event..."), 1);
			Mail_List(0);
			gHtmlControl->RefreshAndDraw();
//			if(feedback->iDataBuffer[data_desc])
//				AppUi()->RunNote1L(&(feedback->iDataBuffer[data_desc]->Des()));
		}
		break;
		
		case mail_read_content:
		{
			//CEikonEnv::Static()->InfoWinL(_L("test"), _L("got read content"));	
			iWaitDlg.Note(_L("Got read content..."), 1);
			iDBMail->Commit();			
			ProcessPageParameters(iCurrentPageUrl);
		}
		break;

		case mail_read_content2:
		{
//			CEikonEnv::Static()->InfoWinL(_L("test"), _L("got read content2"));	
			iWaitDlg.Note(_L("Got read content..."), 1);
			iDBMail->Commit();		
			ProcessPageParameters(iCurrentPageUrl);
		}
		break;
		
		case mail_send:
		case mail_reply:
		{
			if(feedback->iDataBuffer[data_desc])			
				iWaitDlg.Note(feedback->iDataBuffer[data_desc]->Des(), 1);
				
		}
		break;

		case news_checkcategory:
		{
			iWaitDlg.EndWait();
			c4_View temp = iDBTemp->View("category");
			int count = temp.GetSize();

			if(count > 0)//有更新，第１条说明是该分类是否有更新。以后的是该分类的子分类内容
			{
				iWaitDlg.Note(_L("find updated"), 2);
				//只注明本类的检查时间，其子类需要重新检查
				SetRowRefIntValue(temp[0], "checktime", Dateline());
				
				int cid = FieldIntValue(&temp, "cid", 0);	
				int level = FieldIntValue(&temp, "level", 0);
				
				c4_View category = gDBStore->View("channel");
					
				//先删掉原来的子类。因为服务器可能删除了一些分类
				int num = category.GetSize();
				for(int i = 0; i < num; i++)
				{
					int pid = FieldIntValue(&category, "pid", i);
					
					if(pid == cid)
					{
						category.RemoveAt(i, 1);
						num--;i--;
					}
				}
				
				{
					int i = 0;//always be table of "category"
					int find = FindByInt(&category, "cid", cid);
					if(find < 0)
						category.Add(temp[i]);
					else
						category[find] = temp[i];
				}
				
				//todo, 其中update值置为0,因为父类更新了，其子类均需重新检查更新
				//而这里是和服务器同步，把update值也同步了，所以...
				for(int i = 1; i < temp.GetSize(); i++)
				{
					int tempcid = FieldIntValue(&temp, "cid", i);
					TBuf<10> ttt;
					ttt.Num(tempcid);
					//CEikonEnv::Static()->InfoWinL(_L("tempcid"),ttt);
					
					int find = FindByInt(&category, "cid", tempcid);
					SetRowRefIntValue(temp[i], "update", 0);					
					if(find < 0)
						category.Add(temp[i]);
					else
						category[find] = temp[i];
				
				}
				
				if(level == 1 )//it child's lever is 2
				{
					FillNewsItemOnList(cid);
				}
				else
				{
				//CEikonEnv::Static()->InfoWinL(_L("test"), _L("gg"));
					iCurrentCid = -1;//强制刷新
					FillNewsCataOnTab(cid);
					//再list all items
					if(iHmTab.iAppTabData.Count() > 0)
					{
						int index = iHmTab.GetActiveTabIndex();
						MY_TAB_DATA* data = iHmTab.iAppTabData[index];
						FillNewsItemOnList(data->cid);
					}
				}
			}
		}
		break;

		case news_checklist:
		{
////			iWaitDlg->Note(_L("here"));	
			
			gDBStore->Commit();
//			iWaitDlg.EndWait();
			if(feedback->iDataBuffer[data_desc]){
//				AppUi()->RunNote1L(&(feedback->iDataBuffer[data_desc]->Des()));
				iWaitDlg.Note(feedback->iDataBuffer[data_desc]->Des(),1);	
			
				int index = iHmTab.GetActiveTabIndex();
				MY_TAB_DATA* data = iHmTab.iAppTabData[index];
				int cid = data->cid;
				FillNewsItemOnList(cid);		
			}
			else
				iWaitDlg.EndWait();	

		}
		break;

		case news_read_content:
		{
//			CEikonEnv::Static()->InfoWinL(_L("test"), _L("got read news content"));	
			gDBStore->Commit();			
//			AppUi()->RemoveWaitDialog1L();	
			//replace field with downloaded content
			News_ReadMsg(iPageInfo.pageid);
			//将已经下载的预览图调入
			LoadExistImages();
		}
		break;

		case club_friendadd:
		{
			/*
			CEikonEnv::Static()->InfoMsg(_L("ttg"));
			//fill in the friend list;
			c4_View temp = iDBTemp->View("result");
			int fuid = FieldIntValue(&temp, "uid", 0);			
			TPtrC fusername = FieldStrValue(&temp, "fusername", 0);
			
			c4_View view = iDBClub->View("friend");
			c4_Row row;
			view.Add(row);
			int size = view.GetSize();
			
			SetRowRefIntValue(view[size-1], "fuid", fuid);
			SetRowRefStrValue(view[size-1], "fusername", fusername);
			*/
		}
		break;
		
		case club_friendsearch:
		{
			/*
			c4_View temp = iDBTemp->View("result");
			int fuid = FieldIntValue(&temp, "uid", 0);			
			TPtrC fusername = FieldStrValue(&temp, "fusername", 0);
			//.. tell user already found, then ask him if want to add..
		    iDialog->PreloadPage(_L("confirmfriendsearch.xml"));
		    iDialog->RichEditor()->ReplaceMyField(_L("username"), fusername, true);
			    
		    if(iDialog->ExecuteWithoutLoad())
		    {
				Post(_L("post?club_friendadd"));
		    }
		    */
		}
		break;
		
		case task_info:
		{
			CEikonEnv::Static()->InfoWinL(_L("Info"), *(feedback->iDataBuffer[data_desc]));
		}
		break;
				
		case stock_info:
		{
			/*
			c4_View v = iDBStock->View("stock");
			TPtrC ptr = FieldUnicodeValue(&v, "name", 0);
			TPtrC ptr2 = FieldStrValue(&v, "zhangfu", 0);
			TPtrC ptr3 = FieldStrValue(&v, "dangqian", 0);						
			TBuf<300> buf;
			buf.Format(_L("%S,%S"), &ptr2, &ptr3);
			
			iEditor->ReplaceMyField(_L("name"), ptr);
			iEditor->ReplaceMyField(_L("dangqian"), ptr3);			
			iEditor->ReplaceMyField(_L("zhangfu"), ptr2);
			iEditor->HandleTextChangedL();
			
			LoadStockImage();*/
		}
		break;
		
		
		default:
		{
			CEikonEnv::Static()->InfoWinL(_L("Feedback"), _L("not defined command"));
			CEikonEnv::Static()->InfoWinL(_L("Feedback"), feedback->iDataBuffer[data_func]->Des());
		}
		break;
	}
	
	if(feedback->iDataBuffer[data_func]->Des() == _L("pm_checkdata"))	
	{
		CEikonEnv::Static()->InfoWinL(_L("test"), _L("checkdata"));
	}
}

void CMyDataCenter::PopMenu()
{
	if(iMenuStr != _L(""))
	{
		c4_View view = gDBStore->View("menu");		
		TBuf8<256> str8;
		str8.Copy(iMenuStr);
		char* path = (char *)str8.Ptr();
		path[iMenuStr.Length()] = 0;
		
		int find = FindByStr(&view, "name", path);
		if(find < 0)
			return;

		TPtrC8 ptr8 = DBUtil::Static()->FieldUtf8Value(&view, "content", find);
		HBufC* ptr = CnvUtfConverter::ConvertToUnicodeFromUtf8L(ptr8);
		iPopMenu.PopUp(*ptr);

		CleanupStack::PushL(ptr);
		CleanupStack::PopAndDestroy(ptr);
	}
}

void CMyDataCenter::RenderListItemL(CHtmlElement* aElement, TInt aIndex) 
{ 
//在这里，完成对aElement的渲染，你可以任意改变它的样式和属性。 

	_LIT(KIdTitle, "title"); 
	CHtmlElement* icon = aElement->ElementByTag(KHStrImg); 
	CHtmlElement* title = aElement->Element(KIdTitle); 
	CHtmlElement* from = aElement->Element(_L("from"));
	CHtmlElement* link = aElement->Element(_L("link"));	
	

	icon->SetProperty(KHStrSrc, _L("mem.mail_left.gif"));
	TBuf<10> tt;
	tt.Num(aIndex);
	c4_View view = iDBMail->View("inbox");
	int index = aIndex;
	int size = view.GetSize();
	if(aIndex > (size-1))index=size-1;
	TPtrC ptr = FieldUnicodeValue(&view, "subject", index);	
	TPtrC ptrfrom = FieldUnicodeValue(&view, "from", index);

	title->SetProperty(KHStrInnerText,ptr);
	from->SetProperty(KHStrInnerText, ptrfrom);
	
	int localid = FieldIntValue(&view, "id", index);
	TBuf<256> linkstr;
	linkstr.Format(_L("mail/readmail.htm?pfunc_readmail(%d)"), localid);
	link->SetProperty(KHStrInnerText, linkstr);
	
	if(ptrfrom == _L(""))
	{
		const TPtrC8 fromaddr8 = FieldStr8Value(&view, "fromaddr", index);
		MyStr16 fromaddr(fromaddr8);
		from->SetProperty(KHStrInnerText, fromaddr.Value());
	}
	//if(...) 
		//title->SetStyle(KHStrFontWeight, KHStrBold); 
//	else 
//		title->SetProperty(KHStrFontWeight, KNullDesC); 

}

//Add the control so it can be get events of key
//call it whithin the MyPopMenu::PopUp or MyDialog::Excute
void CMyDataCenter::AddToStack(CCoeControl* aControl)
{
	if(iActiveView == NULL)	return;
	if(iActiveContainer == NULL) return;
	
	AppUi()->RemoveFromViewStack( *iActiveView, iActiveContainer );		
	AppUi()->AddToStackL( *iActiveView, aControl );
}

//2009.06.02
//为了控制左右键太快，总是在１秒以后才进行Sync
void CMyDataCenter::OnTimer(CMyTimer* timer, int eventid, int extrapara)
{
	if(eventid == 100)
	{
		SyncrosizeActiveTab2();
		iTimer->Cancel();
	}
}

/*
 * 2009.05.22 发现e50上莫明其妙地down,几经周折,知道是tbuf用的太多
 * 导致堆栈出错. 应该尽量用tptrc, hbuf, 以及用函数分化.避免在一个函数
 * (本函数)内使用过多的静态buf
 */
void CMyDataCenter::Post(const TDesC& poststr)
{
	URLInfo funinfo;
	getfuncpara(poststr, funinfo);

	TPtrC postpara(funinfo[1]);
	
	//
	int commandid = CommandIndex(postpara);
	if(commandid == -1)
	{
		CEikonEnv::Static()->InfoMsg(_L("Post:not defined command"));
	}

	//process
	char* postname = NULL;
	TBuf8<128> buf8;
	buf8.Copy(postpara);
	postname = (char *)buf8.Ptr();	
	postname[buf8.Length()] = 0;
	
	c4_View view = gDBStore->View("PostData");	
	int pos = FindByStr(&view, "name", postname);///(char*)TaskCommands[commandid]);
	if(pos < 0)
	{ 
		TBuf<128> msg;
		msg.Format(_L("not find command '%S' in database"), &postpara);
		CEikonEnv::Static()->InfoWinL(_L("post"), msg);		
		funinfo.Reset();
		return;
	}


	TPtrC8 ptrc8 = FieldUtf8Value(&view, "data", pos);
	int len = ptrc8.Length();	
	if(len == 0)
	{
		TBuf<128> msg;
		msg.Format(_L("the record %d is empty, from postdata"), pos);
		CEikonEnv::Static()->InfoWinL(_L("post"), msg);
		funinfo.Reset();
		return;
	}
			
	int extra = 1024;
	HBufC8* iBuf8 = HBufC8::NewLC(len + extra);	
	TPtr8 ptr8 = iBuf8->Des();

	switch(commandid)
	{
		case task_login_bt:
		{
/*			
		    iBtMode = true;
			InitBluetooth();		

			HBufC* iUser = iEditor->GetEditValue(_L("user"));
			iUsername.Copy(iUser->Des());
			HBufC* iPwd = iEditor->GetEditValue(_L("pwd"));			
			TBuf8<128> user;
			user.Copy(iUser->Des());
			TBuf8<128> pwd;
			pwd.Copy(iPwd->Des());
			
			ptr8.Format(ptrc8, &user, &pwd);
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	
*/			
		}
		break;
		
		case task_login2:
		{
			Login(ptrc8);
		}
		break;

		case club_friendadd:
		{
			/*
			c4_View temp = iDBTemp->View("result");
			int fuid = FieldIntValue(&temp, "uid", 0);			
			TPtrC fusername = FieldStrValue(&temp, "fusername", 0);
				
			TBuf8<50> uid8;
			uid8.Copy(iUserid);
			TBuf8<50> fusername8;
			fusername8.Copy(fusername);
				
			ptr8.Format(ptrc8, &uid8, fuid, &fusername8);
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);
			*/
		}
		break;
		
		case club_friendsearch:
		{
			/*
		    if (iDialog->Execute(_L("inputfriendsearch.xml")))
		    {
				HBufC* fusername = iDialog->GetPrompt();
				TBuf8<128> username;
				username.Copy(*fusername);
				
				ptr8.Format(ptrc8, &username);
				IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);
		    }
		    */
		}
		break;
		
		case mail_config:
		{
			/*
			HBufC* iAccount = iEditor->GetEditValue(_L("account"));
			HBufC* iPwd = iEditor->GetEditValue(_L("password"));
			TBuf8<128> account;
			account.Copy(iAccount->Des());
			TBuf8<128> pwd;
			pwd.Copy(iPwd->Des());
			
			//save to database
			//该表内只有一个记录
			c4_View view = iDBMail->View("account");
			if(view.GetSize() > 0)
			{
				SetRowRefStrValue(view[0], "mailaddress", *iAccount);
				SetRowRefStrValue(view[0], "password", *iPwd);				
			}
			//post it
			ptr8.Format(ptrc8, &iUserid, &account, &pwd);			
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);*/				
		}
		break;
		
		case mail_check_list:
		{
			MailCheckList(ptrc8);
		}
		break;

		//如果数据库里也是utf8, 那么用format可能就无法传递中文，需要将其先转为ansi。
		//另一个方法就是手工创建xml
		case mail_send:
		{
			MailSend(ptrc8);
		}
		break;

		case mail_reply:
		{
			MailReply(ptrc8);
		}
		break;
				
		case mail_read_content:
		{
			MailContentRead(ptrc8, funinfo[2]);
		}
		break;

		case news_checkcategory:
		{
			NewsCategoryCheck(ptrc8, funinfo[2], funinfo[3]);
		}
		break;
		
		case news_checklist:
		{
			int channelid = 0;
			TLex lex(funinfo[2]);
			lex.Val(channelid);
			
			NewsListCheck(ptrc8, channelid);
		}
		break;

		case news_read_content:
		{
			int pageid = 0;
			TLex lex(funinfo[2]);
			lex.Val(pageid);
			
			NewsContentRead(ptrc8, pageid);
		}
		break;

		case mystock_add:
		{
			/*
			TBuf<128> para;
			para.Copy(funinfo[2]);

			TBuf8<10> code;
			code.Copy(para);
//			CEikonEnv::Static()->InfoWinL(_L("mystock"),para);

			TBuf8<128> userid8;
			userid8.Copy(iUserid);
			
			ptr8.Format(ptrc8, &userid8, &code);
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	*/
		}
		break;
		
		case mystock_info:
		{
			CEikonEnv::Static()->InfoWinL(_L("mystock"),_L("para"));	
		}
		break;

		case stock_info:
		{
			/*
			TBuf<128> para;
			para.Copy(funinfo[2]);

			TBuf8<10> code;

			if(para == _L(""))
			{			
				TBuf<50> temp;
				iEditor->GetFieldValue(_L("code"), temp);
				code.Copy(temp);
			}
			else
			{
				iEditor->ReplaceMyField(_L("code"), para);
				code.Copy(para);
			}
			
			ptr8.Format(ptrc8, &code);
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptr8, this);	*/
		}
		break;

		case stock_query:
		{
			/*
//			MyDialog* dialog = MyDialog::NewL(TRect(0,0,100,100));
//			dialog->ExecuteLD(R_MODAL_DIALOG);
		    if (iDialog->Execute(_L("input1.xml")))
		    {
//        		CEikonEnv::Static()->InfoMsg(*(iDialog->GetPrompt()));
				HBufC* iCode = iDialog->GetPrompt();
				TBuf<128> poststr;
				poststr.Format(_L("post?stock_info(%S)"), iCode);
				
				Post(poststr);
		    }
        	else 
	        	CEikonEnv::Static()->InfoMsg(_L("excute fal"));*/
		}
		break;
		
		default:
		{
			CEikonEnv::Static()->InfoMsg(_L("default defined command"));
			IssueHTTPPostL(KRemoteIP, _L8("*.*"), ptrc8, this);	
		}
		break;
	}//end switch
	
	CleanupStack::PopAndDestroy(iBuf8);
	
	funinfo.Reset();	
}

void CMyDataCenter::StartBrowser(const TDesC& aUrl)
{
	HBufC* param = HBufC::NewLC( 256 );

	param->Des().Format( _L( "4 %S" ),&aUrl );

	///param->Des().Format( aUrl );
	///param->Des().Copy(_L("4 wap.yahoo.com/"));
	
	// Wap Browser's constants UId
	TInt KWmlBrowserUid = 0x10008D39; ///0x10008D39 - Service; 0x1020724D -- app
	// 0x101f8532
	
	TUid id( TUid::Uid( KWmlBrowserUid ) );
	
	TApaTaskList taskList( CEikonEnv::Static()->WsSession() );
	TApaTask task = taskList.FindApp( id );
	if ( task.Exists() )
	{
		task.BringToForeground();
		HBufC8* param8 = HBufC8::NewLC( param->Length() );
		param8->Des().Append( *param );
		task.SendMessage( TUid::Uid( 0 ), *param8 ); // Uid is not used
		CleanupStack::PopAndDestroy(); // param8
	}
	else
	{
		RApaLsSession appArcSession;
		User::LeaveIfError(appArcSession.Connect()); // connect to AppArc server
		TThreadId id;
		appArcSession.StartDocument( *param, TUid::Uid( KWmlBrowserUid ), id );
		appArcSession.Close();
	}
	CleanupStack::PopAndDestroy(); // param
}

bool CMyDataCenter::ProcessLink(const TDesC& paras, bool addhistory)
{
	if(iHmTab.iTabNum== 0)
	{
		//强迫下次出现apptab
		iTabGroupUid = -1;
		iCurrentCid = -1;
	}

	//note!
	//within parsexmlfile, it call cleanresource, the paras will be deleted
	TBuf<256> path;
	path.Copy(paras);
	iCurrentPageUrl.Copy(paras);
	
	//visit remote msp file
	if(paras.Find(_L("http://")) == 0)
	{
		StartBrowser(paras);
		return false;
	}
	else if(paras.Find(_L("post?")) == 0)
	{
		Post(paras);
		return false;
	}
	//CEikonEnv::Static()->InfoWinL(_L("process4"), paras);
/* was for cmd://, not should use self?func
	PM_Send();
	Mail_Config();
	*/

	//convert into unix path
	for(int i = 0; i < path.Length(); i++){
		if(path[i] == '\\') path[i] = '/';
	}

//CEikonEnv::Static()->InfoMsg(path);	
	LoadMemPage("syspage", path, addhistory);
}

//从远程网站调入股票的行情图
void CMyDataCenter::LoadStockImage()
{
////	iImgDownTask.method = 2;	
////	_LIT(KLocalStockImg, "c:\\data\\itest\\stock.gif");	
////	iImgDownTask.dest.Copy(KLocalStockImg);
////	
////	//
////	TBuf<50> temp;
////	iEditor->GetFieldValue(_L("code"), temp,_L("600016"));
////	
////	TBuf8<10> code;
////	code.Copy(temp);
////	_LIT8(KRemoteStockImg1, "http://3g.sina.com.cn/3g/static/images/finance/stock/daily/sh%S.gif");
////	_LIT8(KRemoteStockImg2, "http://3g.sina.com.cn/3g/static/images/finance/stock/daily/sz%S.gif");
////	TBuf8<256> url;
////	if(code[0] == '0')
////		url.Format(KRemoteStockImg2, &code);
////	else
////		url.Format(KRemoteStockImg1, &code);
////	
////	IssueHTTPGetL(url, this);
}

bool CMyDataCenter::ProcessPageParameters(const TDesC& paras)
{
	URLInfo urlinfo;
	getfuncpara(paras, urlinfo);
	
	if(urlinfo[1] == _L(""))
	{
		urlinfo.Reset();	
		return false; //no additional page function
	}
	
	int pagefuncid = CommandIndex(urlinfo[1]);
	
	switch(pagefuncid)
	{
		case func_test:
		{
//			iWaitDlg.Note(_L("download test...."), 1);	
//			iHttpDownload->GetRequestL(_L8("http://www.haomail.net/down.txt"));
			TestMe();
		}
		break;
		
		case func_plugin:
			{
				PlugIn();
			}
			break;
		
		//将用户上次输入的用户信息调入
		case task_login2:
		{
			c4_View view = gDBStore->View("login");
			const TPtrC8 user8 = FieldStr8Value(&view, "username", 0);
			MyStr16 username(user8);
			CHtmlElement* eUsername = gHtmlControl->Element(_L("username"),0);
			if(eUsername != NULL){
				eUsername->SetProperty(KHStrValue, username.Value());
			}
			const TPtrC8 pass8 = FieldStr8Value(&view, "password", 0);
			MyStr16 password(pass8);
			CHtmlElement* ePassword = gHtmlControl->Element(_L("password"),0);
			if(ePassword != NULL){
				ePassword->SetProperty(KHStrValue, password.Value());
			}
			
			gHtmlControl->RefreshAndDraw();
		}
		break;
		
		case task_update:
		{
			c4_View temp = iDBTemp->View("software");
			TPtrC ptr = FieldUnicodeValue(&temp, "desc", 0);
			CHtmlElement* changelog = gHtmlControl->Element(_L("changelog"),0);
			if(changelog != NULL)
			{
				changelog->SetProperty(KHStrInnerText, ptr);
			}
		}
		break;
		
		case func_mailenter:
		{
			c4_View temp = iDBTemp->View("login");
			const TPtrC8 ptr8 = FieldStr8Value(&temp, "mailaccount", 0);
			MyStr16 ptr(ptr8);
			
			int result = FieldIntValue(&temp, "result", 0);
			if(result == 0)
				LoadMemPage("syspage", _L("mail/index2.htm"));	
			else{
				LoadMemPage("syspage", _L("mail/index.htm"));	
				CHtmlElement* container = gHtmlControl->Element(_L("mail"),0);
				if(container){
					container->SetProperty(KHStrInnerText, ptr.Value());
					gHtmlControl->RefreshAndDraw();		
				}
			}
			
			//iWaitDlg.Note(ptr, 1);
			
		}
		break;

		//将friend list 调出来
		case club_pf_friendlist:
		{
			/*
			c4_View view = iDBClub->View("friend");
			int size = view.GetSize();
		
			CPicList* piclist = iEditor->PicList();
			if(piclist == NULL)
				break;

			piclist->Reset();
			piclist->SetLinesPerItem(1);

			for(int i = 0; i < size; i++)
			{
				TPtrC fusername = FieldStrValue(&view, "fusername", i);
				piclist->FillItemText(fusername, _L(""), _L("newpm.gif"));
			}
			iEditor->TextView()->HandleGlobalChangeL();				
			*/
		}
		break;
		
		case func_viewimage:
		{
			LoadImageViewer(0);//activate the container to display
		}
		break;
		
		case mail_config:
		{
			Mail_ReadConfig();
		}
		break;
		
		case func_maillist:
		{
			Mail_List(0);
			gHtmlControl->RefreshAndDraw();
		}
		break;
		
		case func_readmail:
		{
			TLex lex(urlinfo[2]);
			int id;
			lex.Val(id);
			Mail_ReadMsg(id);
		}
		break;
		
		case func_newslist:
		{
			int channelid = 0;
			TLex lex(urlinfo[2]);
			lex.Val(channelid);
			
			int batchid = 0;
			TLex lex2(urlinfo[3]);
			lex2.Val(batchid);
						
			TBuf<128> para;
			para.Format(_L("(%d,%d)"), channelid, batchid);
			
//这里不应该修改channelid
//而应该修改第３个参数，即batchid, para = siteid, channelid, batchid
////			ChangeCurrentHistoryPara(para);
			
			News_List(channelid, batchid);
		}
		break;

		case func_readnews:
		{
			TLex lex(urlinfo[2]);
			int id;
			lex.Val(id);
			News_ReadMsg(id);
			//将已经下载的预览图调入
			LoadExistImages();
//			FindImageToGet();
		}
		break;
		
		case func_downimage:
		{
			/*
			int imgindex = FindImageToGet(); //1-the first image
			if(imgindex < 0)
			{
				CEikonEnv::Static()->InfoWinL(_L("note"), _L("all images downloaded"));
				break;
			}
			*/
		}
		break;
	

		/*
		 * 列出分类到Tab, 同时列出子分类到list
		 * 参数1是Tab上category/channel的所属cid, 参数2个是List中条目的所属category/channel的所属cid
		 */
		case func_sitelist:
		{
			AddSelfHistory(paras, false);
			iHmTab.ShowTab();
			iHmUtil.AdjustClientHeight();			
			int cid = 0;
			TLex lex(urlinfo[2]);
			lex.Val(cid);
			int seltab = 0;
			TLex lex2(urlinfo[3]);
			lex2.Val(seltab);

			FillNewsCataOnTab(cid, seltab);
			
			if(iHmTab.iAppTabData.Count() > 0)
			{
				int index = iHmTab.GetActiveTabIndex();
				MY_TAB_DATA* data = iHmTab.iAppTabData[index];
				FillNewsItemOnList(data->cid);
			}
			else //空数据，需要从远程检查更新
			{
				TBuf<128> poststr;
				poststr.Format(_L("post?news_checkcategory(%d,0)"), cid);
				Post(poststr);
				break;
			}
			
			if(cid >= 1000) break;

			c4_View category = gDBStore->View("channel");
			int find = FindByInt(&category, "cid", cid);
			if(find < 0) break;

			int checktime = FieldIntValue(&category, "checktime", find);
			int updatetime = FieldIntValue(&category, "update", find);
			
			int dateline = Dateline();

			bool check = (checktime > dateline)||((dateline - checktime) > CategoryCheckTime);
			if (check)//超过１天就去检查更新
			{
////				TBuf<128> test;
////				test.Format(_L("%d,%d"), cid, updatetime);
////				CEikonEnv::Static()->InfoWinL(_L("te"), test);
				iWaitDlg.Note(_L("Checking the updating of category...."), 1);
				//注明本类的检查时间
				SetRowRefIntValue(category[find], "checktime", Dateline());
				
				TBuf<128> poststr;
				poststr.Format(_L("post?news_checkcategory(%d,%d)"), cid, updatetime);
				Post(poststr);
			}
			else
				SyncrosizeActiveTab();
	
		}
		break;
		
		case mystock_add:
		{
			/*
		    if (iDialog->Execute(_L("input1.xml")))
		    {
//        		CEikonEnv::Static()->InfoMsg(*(iDialog->GetPrompt()));
				HBufC* iCode = iDialog->GetPrompt();
				TBuf<128> poststr;
				poststr.Format(_L("post?mystock_add(%S)"), iCode);
				
				Post(poststr);
		    }
        	else 
	        	CEikonEnv::Static()->InfoMsg(_L("excute fal"));
	        	*/
		}
		break;
		
		case mystock_info:
		{
			/*
			CEikonEnv::Static()->InfoMsg(_L("herel"));
			Post(_L("post?mystock_info"));*/
		}
		break;
		
		case stock_img:
		{
			//刷新行情
			Post(_L("post?stock_info"));
		}
		break;
		
		//just for menu item, because menu string can not add parameters
		//强制刷新，与远程服务器连接进行检查
		case news_checklist:
		{
			int index = iHmTab.GetActiveTabIndex();
			MY_TAB_DATA* data = iHmTab.iAppTabData[index];	
			//if it's channel tab
			if(data->cid >=1000)
			{
				TBuf<128> channeltorefresh;
				channeltorefresh.Format(_L("post?news_checklist(%d)"), data->cid);
				Post(channeltorefresh);
				data->freshtime = Dateline();
			}
		}
		break;
		
		default:
		{
			CEikonEnv::Static()->InfoWinL(_L("unkown page function"), paras);
		}
		break;
	}	
	
	urlinfo.Reset();	
	return true;
//	CEikonEnv::Static()->InfoWinL(_L("fff"), urlinfo[0]);

//	CEikonEnv::Static()->InfoWinL(_L("fff"), urlinfo[0]);

/*	
	if(paras == _L("pm/index.xml"))
	{
		PM_List(0);
	}
	
	if(urlinfo[1] == _L("pm_list"))
	{
		if(urlinfo[2] == _L("next"))
			PM_List(1);
		if(urlinfo[2] == _L("prev"))
			PM_List(-1);
	}
	else if(urlinfo[0] == _L("pm/viewmsg.xml"))
	{
		PM_ReadMsg();
	}

	else if(urlinfo[0] == _L("mail/config.xml.xml"))
	{
		Mail_Setup();
	}
*/
}


void CMyDataCenter::SetRowRefIntValue(c4_RowRef rowref, char* fieldname, int value)
{
	c4_IntProp intfield(fieldname);
	intfield(rowref) = value;
}

void CMyDataCenter::SetRowRefStrValue(c4_RowRef rowref, char* fieldname, const TDesC& value)
{
	//以后要用hbuf8来处理
	TBuf8<256> str8;
	str8.Copy(value.Left(256));
	
	char* p = (char *)str8.Ptr();
	p[value.Length()] = 0;	
	
	c4_String str(p);
	c4_StringProp strfield(fieldname);
	strfield(rowref) = str;
}

void CMyDataCenter::SetRowRefBinValue(c4_RowRef rowref, char* fieldname, const TDesC8& value)
{
	c4_BytesProp b1(fieldname);		
	TUint8 * buffer = new TUint8[value.Length()];
	memcpy(buffer, value.Ptr(), value.Length());
    c4_Bytes bin = c4_Bytes(buffer, value.Length());
    b1 (rowref) = bin;
    delete buffer;
    
////	view->iScannedbuf += bin.Size();
////	if(view->iScannedbuf > 200000)//200k
////	{
////		view->iScannedbuf = 0;
////		view->ClearBuffer();
////	}    
}

//cancel some loading to avoid down
void CMyDataCenter::CancelLoading()
{
	iHttpImgDown->CancelTransaction();
//	iHmPreview.ClearSnapData();
//	CEikonEnv::Static()->InfoMsg(_L("cancel"));
}
	
void CMyDataCenter::TestMe()
{

}

TLibraryFunction plugin;
void CMyDataCenter::PlugIn()
{
	//RLibrary library;
	User::LeaveIfError( iLibrary.Load(_L("iReadPlugin.dll")));

	//TLibraryFunction plugin=iLibrary.Lookup(1);
	plugin=iLibrary.Lookup(1);
	MMyDll* messenger=(MMyDll*) plugin();


	TInt value = messenger->Load(gHtmlControl, this);
	delete messenger;
	TBuf<10> tt;
	tt.Num(value);
	//CEikonEnv::Static()->InfoMsg(tt);


	//CEikonEnv::Static()->InfoWinL(_L("test"), _L("plugin"));	
	//library.Close();
}

void CMyDataCenter::HandleBufImageLoadEventL(CBufferedImageDecoder* aDecoder, const TDesC& aFileName)
{
	c4_View view = iDBRes->View("image");
	int flag = 0;
	
	TBuf8<256> str8;
	int len = aFileName.Length();
	str8.Copy(aFileName.Right(len-4));
	
	char* path = (char *)str8.Ptr();
	path[str8.Length()] = 0;
	
	int find = FindByStr(&view, "path", path);
	if(find < 0){
		view = iDBInfo->View("pageimages");
		flag = 1;
		find = FindByStr(&view, "imagefile", path);
		if(find < 0)
		{
			view = iDBInfo->View("pagelargeimages");
			flag = 2;
			find = FindByStr(&view, "imagefile", path);
		}
		
		if(find < 0) find = 0;
	}

	//if(flag > 0)
	//iDBInfo->Commit();

	if(flag == 0)
	{
		TPtrC8 ptr = FieldUtf8Value(&view, "data", find);
		aDecoder->OpenL(ptr);
	}
	else
	{
		int pos = FieldIntValue(&view, "datapos", find);
		int size = FieldIntValue(&view, "datasize", find);
		TPtrC8 ptr = iMyImgFile.ImgBlock(pos, size);
		aDecoder->OpenL(ptr);
		iMyImgFile.ReleaseBlock();
	}

/*	
	RFile rFile;

	_LIT(KFileName, "C:\\data\\htmlcontrol\\test.jpg");
	//Open file where the stream text is
	User::LeaveIfError(rFile.Open(CCoeEnv::Static()->FsSession(),
			KFileName, EFileRead));
	
	TInt size;
	rFile.Size(size);
	HBufC8* fileData8 = HBufC8::NewLC(size);
	TPtr8 ptr = fileData8->Des();
	rFile.Read(ptr, size);
		
	aDecoder->OpenL(ptr);
	CleanupStack::PopAndDestroy(1); // filedata8		
	rFile.Close();
*/	
}
bool ggg = false;
_LIT(KIdItem, "mail_listitem");
void CMyDataCenter::HandleHtmlCtlEventL(const THtmlCtlEvent& aEvent)
{
	if( aEvent.iType==THtmlCtlEvent::EOnClick && aEvent.iElement->Id().Compare(_L("grid_item"))==0)
		{
			iHmGridView.HandleHtmlCtlEventL(aEvent);
			return;
		}
	
	if(aEvent.iType==THtmlCtlEvent::EOnClick && aEvent.iElement->Id().Compare(KIdItem)==0) 
		{ 
		//TODO: 响应单击事件
		TInt itemIndex;
		iList->GetProperty(KHStrListSelectedIndex, itemIndex);
		TBuf<200> href;
		CHtmlElement* link = aEvent.iElement->Element(_L("link"));	
		link->GetProperty(KHStrInnerText, href);		
		ProcessLink(href);	
		return;
		}

/*
	if(aEvent.iType==THtmlCtlEvent::EOnClick && aEvent.iElement->Id().Compare(KIdItem)==0) 
	{ 
		//TODO: 响应单击事件 
		TInt itemIndex; 
		iList->GetProperty(KHStrListSelectedIndex, itemIndex); 
		
		//...
		
	} 
*/
	if(aEvent.iType==THtmlCtlEvent::EOnClick)
	{
		TBuf<200> href;
		aEvent.iElement->GetProperty(KHStrHref, href);
		TPtrC id = aEvent.iElement->Id();		

		if(href != _L(""))
		{
			_LIT(KTitle, "Click Link");
//			CEikonEnv::Static()->InfoWinL(KTitle, href);
			ProcessLink(href);	
		}
		else
		{
			if(aEvent.iElement->Id() == _L("listitem"))
			{
				CHtmlElement* link = aEvent.iElement->Element(_L("link"));
				if(link == NULL) return;
				link->GetProperty(KHStrInnerText, href);
//				CEikonEnv::Static()->InfoWinL(_L("Click Link"), href);
				ProcessLink(href);	
			}
			else if(aEvent.iElement->Id() == _L("menuitem"))
			{
				CHtmlElement* link = aEvent.iElement->ElementByTag(_L("a"));
				if(link == NULL) return;				
				link->GetProperty(KHStrHref, href);
				HideMenu();
				ProcessLink(href);	
			}
			else if(aEvent.iElement->Id() == _L("snapimg"))
			{
				//例如正在下载小图片，防止此时点击大图片
				if(iImgDownloading){
					iWaitDlg.Note(_L("can not interven downloading..."), 1);
					return;
				}

				CHtmlElement* link = aEvent.iElement->Element(_L("link"));
				if(link == NULL) return;				
				iHmPreview.LoadLargeImage(link);
//				CEikonEnv::Static()->InfoMsg(aEvent.iElement->Id());
			}
			else 
			{
					CHtmlElement* link = aEvent.iElement->Element(_L("link"));
					link = aEvent.iElement->ElementByTag(_L("a"));
					if(link == NULL) return;				
					link->GetProperty(KHStrHref, href);
					ProcessLink(href);
			}
			
		}
	}
}

bool CMyDataCenter::ProcessTabChange(bool bNextPrev)
{
	bool res = iHmTab.ProcessTabChange(bNextPrev);
	if(res)
		NextPrevAppTab(); 		
	return res;
}

TKeyResponse CMyDataCenter::SuperHandleKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType )
{
	if(iHmUtil.IsDivVisible(_L("iFloat")))
	{
		if(iHmPreview.HandleKeyEventL(aKeyEvent, aType) == EKeyWasConsumed)
		return EKeyWasConsumed;
	}
	
	//CEikonEnv::Static()->InfoMsg(_L("xx"));
	if( aType == EEventKeyDown )
	{ 
		TBuf<40> scanCode; 
		scanCode.AppendNum(aKeyEvent.iScanCode); 
		//CEikonEnv::Static()->InfoMsg(scanCode);
				
		if(aKeyEvent.iScanCode == 165)//right softkeyback
		{
			CancelLoading();

			if(IsMenuVisible())
				HideMenu();
				
			if(GoBack() == false)
	            AppUi()->Exit();
		}
		
		if(aKeyEvent.iScanCode == 164)//left softkey options
		{
			PopMenu();
//			int count = iHistory->Count();
//			if(count >= 0)
//			CEikonEnv::Static()->InfoWinL(_L("current his"), (*iHistory)[count-1]);	
		}
	} 
	
	if(aKeyEvent.iCode == EKeyLeftArrow)
	{
		if(ProcessTabChange(false))
		return EKeyWasConsumed; 
	}
	
	if(aKeyEvent.iCode == EKeyRightArrow)
	{
		if(ProcessTabChange(true))
		return EKeyWasConsumed; 
	}

	return EKeyWasNotConsumed;
}

void CMyDataCenter::LoadStyles()
	{
		c4_View view = gDBStore->View("style");
		
		for(int i = 0; i < view.GetSize(); i++){
			TPtrC8 style = DBUtil::Static()->FieldUtf8Value(&view, "value", i);
			HBufC* styleData = CnvUtfConverter::ConvertToUnicodeFromUtf8L(style);
			gHtmlControl->AddStyleSheetL(*styleData);
			CleanupStack::PushL(styleData);
			CleanupStack::PopAndDestroy(styleData); // styleData
		}
	}

void CMyDataCenter::UnloadPlugin(MMyDll* aPlugin)
	{
		iHmTab.ClearTabData();	
		gHtmlControl->SetEventObserver(this);

		gHtmlControl->ClearStyleSheet();
		LoadStyles();
		
		gHtmlControl->ClearContent();
		iHmTab.Init(gHtmlControl, 3, 0);
		LoadMemPage("syspage", _L("template.htm"),false);	
		LoadMemPage("syspage",_L("index.htm"));
		
		gHtmlControl->RefreshAndDraw();
		
		//iLibrary.Close();
		//AppUi()->Exit();
	}
